C++ Question on ifstream!

J

Jupiter5F

This problem from one of the message boards has got my curiosity going. The
task is to read in lines of data from a file where each line contains a name
and some integers. We want to output the name and the result of adding the
integers. i.e.
~~~~~~~~~~~~~~~~

Frank 3 5 1 9
Jeff 4 9 0
Nancy 2
Ron 1
Tess 4 9 2 1 4
~~~~~~~~~~~~~~~~~
output from above text file should output:

Frank 18
Jeff 13
Nancy 2
Ron 1
Tess 20

My code outputs the first line only. In previous things I've done the input
files were consistent, this is a little different. here's my code:

#include <fstream>
#include <conio>
#include <string>

using namespace std;

int main()
{
string name;
string inputFile = "mylist.txt";
int total = 0;
int number = 0;
ifstream inFile;

inFile.open(inputFile.c_str());
if(!inFile)
{
cout << "Could not open file: " << inputFile << endl;
return 1;
}
inFile >> name;
while(inFile)
{
while(inFile >> number)
total += number;
cout << name << " " << total << endl;
total = 0;
number = 0;
inFile >> name ;
}

getch();
}
 
R

Russell Hanneken

Jupiter5F said:
~~~~~~~~~~~~~~~~

Frank 3 5 1 9
Jeff 4 9 0
Nancy 2
Ron 1
Tess 4 9 2 1 4
~~~~~~~~~~~~~~~~~ [. . .]
while(inFile)
{
while(inFile >> number)
total += number;

The first time this loop is run, it will stop after it attempts to read an
integer from the second line, and runs into the word "Jeff." The loop stops
because the failbit will be set on inFile.
cout << name << " " << total << endl;
total = 0;
number = 0;
inFile >> name ;

This read operation will fail, because the failbit is still set. Then the
outer loop will end, because the expression (inFile) will evaluate to
false--again, because the failbit is set.

The simplest fix is the clear the failbit after you exit the inner loop.
Add this line after "total += number;":

inFile.clear();
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,053
Latest member
BrodieSola

Latest Threads

Top