Segmentation fault with ifstream

Hello,

My program has to read from stdin. Something like cat filename | my_program.

I success to read from cin as:
1
2
3
4
5
6
string line;
while ( getline(cin, line) ) {
	if ( ligne.legth() > 0 ) {
		cout << line << endl;
	}
}


The issue is when data from cin is too heavy. Here with a file with only 2000 lines (the longest is 25 chars), I have a segfault.

Do you have an idea how to fix that?
I tried to count lines, and if count == 100 I do cin.clear() but it is inefficient.

Thanks in advance.
But getline() reads only up to the next newline, so it should not matter how many lines are in the file.
The problem is probably that getline returns cin, in this case.
You could try the following:
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <string>

using namespace std;

int main(void)
{
     string line;
     while(!getline(cin,line).eof())
           if(line.length() > 0)
                cout << line << endl;
}
Use char* in place of string with getline() method. It should work.
I do not think if you are using Lotus version you need the if statement "if(line.length() > 0)
", it will just increase the run time and size of code than it will do the good.
Its good idea to use Lotus version of while statement while(!getline(cin,line).eof())
. It will reduce the compexcity of code as will as improve the performance and save you to overhead of handle error.
Thanks, I use:

! getline(cin,line).eof()
Last edited on
Topic archived. No new replies allowed.