I have to load three arrays from a text file for homework and I can’t figure out why it isn’t working. This is what the text file look like:
Jean Rousseau
1001 15.50
Steve Woolston
1002 1423.20
Michele Rousseau
1005 52.75
Pete McBride
1007 500.32
It’s a name on one line, then an id number and a balance due on the next line separated by a space.
This is my function to import the data:
void InputFromFile(string fileName, int sizes, string namesAr[],
int idsAr[], float balancesAr[])
{
// Variables
int indexCount;
ifstream inFile;
// Initialize
indexCount = 0;
inFile.open(fileName.c_str());
while(inFile && indexCount < sizes)
{
getline(inFile, namesAr[indexCount]);
inFile >> idsAr[indexCount];
inFile.ignore(1000, '\n');
inFile >> balancesAr[indexCount];
inFile.ignore(1000, '\n');
indexCount++;
}
inFile.close();
}
This is what gets added to the array when I output all the items…
Jean Rousseau
1001
0
-1
3.76467e-039
36
3.76457e-039
0
6.57115e-039
7736952
8.40779e-045
7736952
0
You read the first number from the line, then you ignore all the characters until the end of the line, including the second number. You then try to read the next name as if it were a number, and since you aren’t doing any error checking, everything goes wrong.
This
ignoreis entirely unnecessary: there is nothing to ignore between the first and second numbers as the>>will skip over any leading whitespace. The secondignoreis necessary, since you have to skip the newline at the end of the numbers line before usinggetlineto read the next name line. It may be easier for you to use onlygetlineto read data from the file, then parse the numbers line using astringstream. Mixing formatted extraction (>>) with line-based extraction can be difficult to get right.After any input operation, you must check the state of the stream to ensure that an error did not occur. As a simple example:
A stream has a number of state flags and when an extraction fails, the
failflag is set and must be cleared before you continue using the stream.