Well, in this example it might be useful to think of the ifstream as being very much like cin. If you used cin / cout, it might look like this:
1 2 3 4 5 6 7 8
|
int numsets;
cout << "How many different sets of guests are there: ";
cin >> numsets;
for (int i=0; i<numsets; i++)
{
// etc.
}
|
When you use ifstream it is almost the same, except that you don't need the cout, and
cin
is replaced by
numbers
.
1 2 3 4 5 6 7 8 9
|
ifstream numbers("guestnums.txt");
int numsets;
numbers >> numsets;
for (int i=0; i<numsets; i++)
{
// etc.
}
|
One other comment. It's usually not a good idea to use eof() in a while loop like this,
while (! numbers.eof() )
. If you're just starting out, it's best to stop using that now, rather than having to unlearn it later.
What's the alternative? Well, if you just wanted to read all the numbers from the file, you might do it like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
char filename[] = "guestnums.txt";
ifstream numbers(filename);
if (!numbers.is_open())
{
cout << "Unable to open file: " << filename << endl;
return 1;
}
int num;
int count = 0;
while (numbers >> num)
{
cout << num << " ";
count++;
}
cout << "\nFile contained " << count << " numbers" << endl;
|
and if you wanted to do a similar thing on a line by line basis, it might be done this way, making use of a stringstream to access the contents of each line just as though it was a file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
string line;
while (getline(numbers, line))
{
int count = 0;
int num;
istringstream ss(line);
while (ss >> num)
{
cout << num << " ";
count++;
}
cout << "\nLine contained " << count << " numbers\n" << endl;
}
|