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