why getline() only outputs newline

Nov 18, 2011 at 10:31pm
Hi, I have a file called "seq.txt" which just includes one line of protein sequence with a newline character at end. It's like:

MISLIAALAVDRV

I wrote a program to read the file:

#include<iostream>
#include<fstream>
#include<string>
#include<cmath>
#include<sstream>
#include<map>
#include<vector>
#include<assert.h>

using namespace std;

int main()
{
ifstream input_data;
ofstream output_data;

input_data.open("seq.txt");
string seq;
getline(input_data,seq);
input_data.close();
cout << seq << endl;
return 0;
}

However, the output is nothing but a newline character. Anyone know what's going on? Thank you and my OS is Windows XP.
Nov 18, 2011 at 11:37pm
Is there perhaps a blank line before the text?
Nov 18, 2011 at 11:52pm
Getline will read everything until it hits a newline or a delimiter if you supply a third argument as the delimiter.

You must have a newline at the beginning.

Try:


1
2
3
4
5
6
7
8
9

input_data.open("seq.txt");
string seq;

while (input_data) {
getline(input_data, seq);
cout << seq << endl;
}
input_data.close();



This will read until a newline is hit, cout it, and read again until the end of file is reached. This will print it out eventually. lol


Also, you might want to check if the file even opened by just simply writing:

1
2
3
4
if (input_data)
       // read stuff
else 
     cout << "error: file corrupt or missing\n";

Last edited on Nov 18, 2011 at 11:59pm
Topic archived. No new replies allowed.