Hello all. I'm almost certain this question has been posted before, but I couldn't find it--I apologize if it's a repeat.
Anyway, I'm having a peculiar problem using getline when reading to a file. I know exactly how the file will be formatted, except the presence of comments at the end of a line is optional. Therefore I use a getline to grab the whole line out of the file, then read to my arrays what I need and dump the rest. The problem is that if a line ends immediately after a number I need to input (i.e. '27\n' instead of '27 \n') without a space or other character, the NEXT getline pulls in all zeros. So my input file looks like
10 20 5 !test comment
0 1 2
5 5 5 5 5 5 5 5 5 5
et cetera
So long as line 2 ends with a comment or a space, getline reads in the file just fine. However, if not, my 10 element array that should be filled with 5s is filled with zeros. A part of the code is below. I know it's a little obtuse, but I need to be able to handle 5.0*10 instead of 10 5s. I haven't implemented that yet but this is in preparation for that.
std::fstream infile(this->meshfile.c_str(),std::ios::in);
if (infile.fail()) {
std::cout << "Mesh file I/O error." << std::endl;
return 1;
}
infile.getline(commentBuffer,bufsize);
temp = commentBuffer;
std::istringstream in(temp.c_str(),std::ios::in);
in >> this->nx;
in >> this->ny;
in >> this->nz;
//Get origin
infile.getline(commentBuffer,bufsize);
temp = commentBuffer;
in.str(temp);
//std::istringstream in(temp.c_str(),std::ios::in);
for (ii=0;ii<=2;ii++) {
in >> this->meshorigin(ii);
}
this->meshdx.resize(this->nx);
this->meshdy.resize(this->ny);
this->meshdz.resize(this->nz);
this->nmod = nx*ny*nz;
infile.getline(commentBuffer,bufsize);
temp = commentBuffer;
std::cout << temp << std::endl;
in.str(temp);
ii=0;
while (ii <= nx-1) {
in >> this->meshdx(ii);
ii++;
}
infile.getline(commentBuffer,bufsize);
temp = commentBuffer;
in.str(temp);
ii=0;
while (ii <= ny-1) {
in >> this->meshdy(ii);
ii++;
}
infile.getline(commentBuffer,bufsize);
temp = commentBuffer;
in.str(temp);
ii=0;
while (ii <= nz-1) {
in >> this->meshdz(ii);
ii++;
}
I should note that getline is reading the correct string. If I output temp it is filled with the proper numbers. However, the >> operator is failing. Why would it do this if the string wasn't input with a space at the end? Doing
temp += " \n";
didn't work either.
Thanks in advance for the help. Sorry for the long post--I was trying to be comprehensive.
Cheers!
Andy