Frage

Ok so this is killing me at the moment cause its such a simple part of my program that just doesn't want to work. I'm reading data from a textfile to use in a GA.

The first getline() works perfectly, but the second one doesn't want to write any data into my string. When i cout the string it doesn't show anything.

Here is the code:

ifstream inFile;
inFile.open(fname.c_str());
char pop[20], mut[20];

inFile.getline(pop,20);
cout << pop;
inFile.getline(mut,20);
cout << mut; //this outputs nothing

Thanks for any help in advance. A sample form my file: there is no line between them mutation is the line straight after population

Population size: 30
Mutation: 20

Keine korrekte Lösung

Andere Tipps

Your file's first line is 20 characters long (19+new line) but pop[20] can only contain 19 (because the last one is reserved for the null terminator '\0').

When istream::getline stops because it has extracted 20-1 characters, it doesn't discard the new line delimiter (because it was never read). So the next getline just reads the end of the first line, discarding the new line.

That's why you get nothing in the second string.

Your problem is that the length of your input line exceeds the length of the buffer which must hold it.

The solution is to not use character arrays. This is C++, use std::string!

std::ifstream inFile;
inFile.open(fname.c_str());

std::string pop;
std::getline(inFile, pop);
cout << pop << "\n";

std::string mut;
std::getline(inFile, mut);
cout << mut << "\n";

I think you need to find out what the problem is. Add error checking code to your getline calls, refactor the (simple) code into a (simple) function, with a (simple) unittest. Possibly, your second line is longer than the assumed 20 characters (null-term included!).

For an idea of what I mean, take a look at this snippet.

try something like

while (getline(in,line,'\n')){
    //do something with line
}

or try something like

string text;
string temp; 
ifstream file;
  file.open ("test_text.txt");

  while (!file.eof())
  {
    getline (file, temp);
    text.append (temp); // Added this line
  }
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top