If you intend to use
argv[1]
. you should first check that
argc
is greater than one.
My first thought on looking at the file data was a
struct
could be useful. It would contain firstname, lastname, and an array or vector of integers.
I didn't follow up on that, here I just focus on reading the file. This is incomplete, it may point the way.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
|
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
ifstream fin("data.txt");
string word;
int number = 0;
fin >> word >> number >> ws;
if (word != "R:")
{
cout << "unexpected input " << word << "\nexiting\n";
return 1;
}
cout << "number = " << number << '\n';
for (int i=0; i<number; ++i)
{
string line;
if (getline(fin, line))
{
istringstream ss(line);
string firstname;
if (ss >> firstname)
cout << "first name: " << firstname << '\n';
}
}
}
|
The important thing when reading from a file is to not assume that everything works, after each file access, check that it worked. Hence the if statements at lines 16 and 26. That's a minimum, there are a couple more checks that I omitted.
The next part which I think is the key to solving your task is the use of a stringstream at line 28. This allows a string to be treated just like it is a file, you can read from it in the same way. I only read the first string at line 30 - again with a check to see whether it succeeded. The second name could be read in the same way (as part of the same statement perhaps).
To read the integers, I'd suggest a while loop since there is a variable quantity.
1 2 3
|
int n;
while (ss >> n)
// do something
|