views:

232

answers:

3

I am reading in a file with a format similar to:

TIME, x, y, z
00:00:00.000 , 1, 2 , 3
00:00:00.001 , 2 , 3 , 4

etc, and code similar to the following:

std::ifstream& istream;
char buffer[15];
double seconds, hours, mins; // initialised properly in real code

// to read in first column
istream.get(buffer, 14, ',');

int scanned = std::sscanf(buffer, "%d:%d:%lf", &hours, &mins, &seconds);

It reads in the first column fine for most of the time. However, occasionally the sscanf fails, and when I check what is in the buffer using the Codegear debugger I see that it has read in \000:00:023 for example. For some reason it is collecting a null character ,\0, at the front. When I look in the text file, it appears to be the same format as all the other time values that were read in correctly. Why is it occasionally adding a null character? And is there a work around?

+2  A: 

You have read a blank line, or you are trying to read past the end of the file.

The first character is \0, which signifies the end of the string.

Any characters after that are untouched memory.

Shmoopty
But it only happens to some of the time values that I read in and the formatting is consistent for all the rows. So why is it reading a blank line?
Seth
Does a hex editor verify that there are not nulls in the text file? Are you checking istream.eof()? istream.bad()? istream.fail()?
Shmoopty
Yes - it was actually correctly reading the last time value. However, the error was occurring on the next loop when it would try and read past the end of the file. I was confused as the debugger was showing the last time value read in the buffer with the `\0` at the front of it.
Seth
+2  A: 

try this and see..

ifstream inpfile("sample.txt");
char buffer[15];
inpfile.ignore(80, '\n');
while (!inpfile.eof())
{

 inpfile.get(buffer, 14, ',');
 int hrs, mins;
 double secs;
 hrs = mins = secs = -1;
 sscanf_s(buffer, "%d:%d:%lf", &hrs, &mins, &secs);
 cout << "hrs:" << hrs << "\t"
  << "mins:" << mins << "\t"
  << "secs:" << secs 
  << endl;
 inpfile.ignore(80, '\n');
}
Jagannath
A: 

most likely you have a trailing comma in your input file somewhere. or perhaps more than 14 characters of whitespace after the last number on a line.

John Knoeller