Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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');
}

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top