开发者

C++ Homework: Parallel Arrays from text file

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开发者_StackOverflow 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


inFile >> idsAr[indexCount];
inFile.ignore(1000, '\n');

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 ignore is entirely unnecessary: there is nothing to ignore between the first and second numbers as the >> will skip over any leading whitespace. The second ignore is necessary, since you have to skip the newline at the end of the numbers line before using getline to read the next name line. It may be easier for you to use only getline to read data from the file, then parse the numbers line using a stringstream. 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:

if (!(inFile >> idsAr[indexCount]) {
    /* input failed; handle error as appropriate */
}

A stream has a number of state flags and when an extraction fails, the fail flag is set and must be cleared before you continue using the stream.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜