I am trying to take a string from dna file and output the rna sequence of it on the dna2 file. For example if the 1st file had:
AGTGTGCGTC
GTCGATCGCT
output on 2nd file should be:
TCACACGCAG
CAGCTAGCGA
#include <iostream>
#include <string>
#include <fstream>
usingnamespace std;
int main()
{
char dna[100];
char dna2[100];
int size;
ifstream infile;
ofstream outfile;
int length;
infile.open("dna.txt");
outfile.open("dna2.txt");
if (infile.fail())
{ cout<<"Error File cannot be open!"<<endl;
exit(1);
}
infile>>dna;
while (!infile.eof())
{
length = strlen(dna);
for (int i=0; i<length;i++)
{
if (dna[i]=='A')//Takes A and replaces with T
{
dna2[i]=='T';
}
if (dna[i]=='T')//Takes T replaces with A
{
dna2[i]=='A';
}
if (dna[i]=='G')//Takes G replaces with C
{
dna2[i]=='C';
}
if (dna[i]=='C')//Takes C replaces with G
{
dna2[i]=='G';
}
}
outfile <<dna2<<endl; //supposed to output the new string on textfile
}
infile.close();
outfile.close();
system ("pause");
return 0;
}
Your code should not even compile: for strlen you need to include <cstring>
Additionally line outfile <<dna2 has undefined behavior (as dna2 is not null-terminated)
Also your loo will either not execute (if there is no whitespaces/newlines in file) or will be infinite.
Never loop on .eof(). It does not work as you think.
Ok I fixed up my code a little bit, thanks for the help!! I am using Dev C++ maybe its a compiler issue. But one last problem it writes on the file but the output should look like this: CAATCAGCTACG
CAATCAGCTACA
CAATCAGCTACT
but the output is this: CAATCAGCTACGCAATCAGCTACACAATCAGCTACT
I know my output, outputs individual characters one at a time, but I can't think of any other ideas.
Output newline after you done with the string.
And you have the problem again: rna contains 0 elements, so rna[i] is invalid and can lead to crashes.
You still not fixed looping on eof problem: it is a very weak construct which can break from slightlest modification of input data or your code.
You do not need to close files manually. It is done for you in the destructor.
You should prefer to open files in constructor.
And use standard algorithms.
Thank you so much you were such a great help! :D and I never knew eof was bad since many online examples and codes seem to have it. I will try avoiding it in future use