Jump to content

Reading information from a .txt file

- - - - -

  • Please log in to reply
2 replies to this topic

#1
Willum

Willum

    Newbie

  • Members
  • PipPip
  • 10 posts
So I'm trying to recreate a problem for a little bit of a challenge, which is basically a DNA codon to amino acid converter. I thought it would be relatively simple, it pulls the codons from a .txt file (dna.txt) and then going three characters at a time (which is a codon) it uses if statements to match the codon up to the codon relating to the amino acid and writes it to another text file. I know that's not a very 'effecient' route to take, but its all I know how to do at the moment (if anyone has an easier method for beginners and cares to explain it in layman's terms that'd be great too!). But the main part of the problem I'm having right now is the fact that my while loop to pull the text from doesn't work. Individually it works, but together it doesn't! Would anyone care to help out a failure in distress?

#include <iostream>

#include <fstream>

#include <string>


using namespace std;


int main(){


char codon[4];

ifstream a_file("dna.txt");

/*

//This works individually

a_file.get(codon, 4);

cout<<codon;                    

*/ 


//But with just the loop, it doesn't!!

a_file.get(codon, 4);

while(!a_file.eof()){

    cout<<codon;

    a_file.get(codon, 4);

    }

}


Thank you so much in advance!

#2
Flying Dutchman

Flying Dutchman

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 889 posts
  • Location:::1
What's the txt file format?

Anyways, the problem is that you (probably) read past EOF and it becomes an endless loop. You first have to check if you can read 3 characters and then read it, if possible. See seekg, tellg and peek methods.
A conclusion is where you got tired of thinking.
#define class struct    // All is public.

#3
kernelcoder

kernelcoder

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 282 posts
  • Location:Dhaka
  • Programming Language:C, Java, C++, C#, Visual Basic .NET
  • Learning:Objective-C, PHP, Python, Delphi/Object Pascal
Yeah, I'm repeating the question from 'Flying Dutchman'.

However, I think following code is better to use than your posted code (considering that your file will contain characters multiple of 4).


char codon[4];
ifstream a_file("dna.txt");
while(!a_file.eof()){
	a_file.get(codon, 4);
	cout<<codon;
}





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users