My question is, why can I use the variables first, second, and third for numbers in a file? What if I wanted to add the second, third, and fourth numbers? Why/How does it know what number goes with those variables?
The following code would take numbers from a file. Let's say this file contains the numbers 1, 2, 3... and so on, each on their own line. The code would then add the first, second and third numbers ( numbers 1, 2, and 3 in the file) and put strings and the sum in a different file.
The Code:
#include <fstream>
int main()
{
using namespace std;
ifstream in_stream;
ofstream out_stream;
in_stream.open("infile.dat");
out_stream.open("outfile.dat");
int first, second, third;
in_stream >> first >> second >> third;
out_stream << "The sume of the first 3\n"
<< "numbers in infile.dat\n";
<< "is " << (first + second + third)
<< endl;
in_stream.close();
out_stream.close();
return 0;
}
The names 'first', 'second' etc are just names and could be anything. They could be in any order. Try it by changing the order in which they appear in the in_stream >> first ... line.
If the numbers were read in to an array eg a[0], a[1] etc then the indexing would make the ordering within the name significant/meaningful.
The streams do some rudimentary parsing on the data. Basically they just break up the input into chunks separated by whitespace and they convert the individual chunks based on what type was passed as the right hand side operand for >>.
For example, "42 37 85" is treated as "<first chunk> <second chunk> <third chunk>".
<first chunk> = "42"
<second chunk> = "37"
<third chunk> = "85"
When you do in_stream >> first, in_stream treats <first chunk> as an integer, and therefore converts the string "42" into the integer 42 and stores it in the variable.
And so on.
So, I could technically call the first number "ralph" and it would have the same effect?
And I wouldn't be able to add the second, third and fourth unless I first declared the first number, and excluded it from my addition equation, right?