I was wondering how one might go about the following:

I am reading in data from a file using getline(inputFile, tempString). Some of this information has to stay in string format, and other information must be converted to floats, ints, etc.

I anticipate there being a problem if there is an error in the file and one of the pieces of data that should be read into an int is read into a string. For instance, if there were a file as follows:

100             should be read and converted to int
100.23          should be read and converted to a float
100 spring ln   should be read and stay a string
Michael         should be read and stay a string
101             should be read and converted to int
100.50          should be read and converted to float
101 spring ln   should be read and stay a string
100.58          should be read and stay a string --- WOULD CREATE A NOT SO OBVIOUS ERROR
102 spring ln   should be read and converted to int --- OBVIOUS ERROR
Steven          should be read and converted to float --- OBVIOUS ERROR

the code that is reading the file is a loop until EOF. Is there any way to check for the not so obvious error?

Rather than treat each line as separate and independent, collect them in a record where you can validate each field as it relates to the others. So for line 8 you'd be looking for a name, correct? Digits are a clear case of error when looking for a name, so that would fail the validation check and subsequently cause you to stop reading the file because it's clearly malformed.

what does the actual contents of the file look like?

first name
last name
address
id number
credits completed
quality points

I have started working through this. Here is one issue that I have encountered:
when converting an int or float from a string, if it converts a "0" to a 0, the program sees it as an error. Here is the code.

if(!(id = atoi(qual.c_str()))) {
    cout << "***Invalid quality points read from file. Quiting.***" << endl;
    system("pause");
    exit (EXIT_FAILURE);
}

In this case, 0 quality points is an acceptable value. Should I create nested if's to see first if the number is a 0?

when converting an int or float from a string, if it converts a "0" to a 0, the program sees it as an error.

That's one of the primary reasons why you shouldn't use atoi(). The other reason is that if the string doesn't represent a number, you invoke undefined behavior. I posted an example not to long ago on how to properly use strtol() as a replacement for atoi(): Click Here.

However, since this is C++, I'd favor a stringstream (which includes validation that doesn't affect the result), or C++11's stoi() (which will throw an exception for errors rather than overload the return value).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.