Needing help reading characters from a .txt file

For an assignment I am needing to read characters from a text file and they are set up like this: ACTCACGCATCGACGT. I am supposed to read the file, output an error if there is any non-nucleotides and calculate the total number of the nucleotides. Then find the total of each nucleotide A, T, G, and C.

This what I currently have and it is not working for the first part:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{

ifstream idata;
char ch;
int A=0, T=0, G=0, C=0;

idata.open("dnaSequence.txt");

idata.get(ch);

while(idata)
{
if ( ch =='A')
A++;
else if (ch == 'T')
T++;
else if (ch == 'G')
G++;
else if (ch == 'C')
C++;

}

idata.get (ch);

cout<< ch << endl;
cout<<"A= " << A <<"\nT= " << T << "\nG= " << G << "\nC= " << C <<endl;


return 0;
}



You need to read the ch from the file within the while loop. Consider (not tried):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
	int A {}, T {}, G {}, C {};

	ifstream idata("dnaSequence.txt");

	for (char ch; idata.get(ch); ) {
		if (ch == 'A')
			++A;
		else if (ch == 'T')
			++T;
		else if (ch == 'G')
			++G;
		else if (ch == 'C')
			++C+;
	}

	cout << "\nA= " << A << "\nT= " << T << "\nG= " << G << "\nC= " << C << '\n';
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <map>
using namespace std;

istringstream idata( "ACTCACGCATCGACGT" );    // Simulated data file

int main()
{
// ifstream idata( "dnaSequence.txt" );
   const string BASES = "ACGT";
   map<char,int> dna;   for ( char c : BASES ) dna[c] = 0;
   int length = 0;

   bool ok = true;
   for ( char c; idata >> c; )
   {
      if ( BASES.find( c ) == string::npos )
      {
         cout << "Nooo! Non-DNA.";
         ok = false;
         break;
      }
      dna[c]++;
      length++;
   }      

   if ( ok )
   {
      cout << "Number of nucleotides = " << length << '\n';
      for ( auto pr : dna ) cout << pr.first << ": " << pr.second << '\n';
   }
}


Number of nucleotides = 16
A: 4
C: 6
G: 3
T: 3
Last edited on
Topic archived. No new replies allowed.