How do I read the file? & how exactly does my program see the file? What role do newlines, spaces, commas play in my txt file? How do I read a file line by line? |
A file, like anything else in a computer, is a sequence of bytes. If it's a text file, the value of each byte represents some character (it's ASCII I'm talking about. Unicode is a bit more complicated). For example, 97 is 'a', 32 is a white space and 13 followed by 10 marks the end of a line (you don't need to know these). Reading the file byte by byte yourself would be a bit of a pain, so there are libraries meant to make it more comfortable for you.
Now, about your example.. The key to successfully reading the contents of a file is knowing what they look like and knowing how you want to store them. You need to analyse each case separately. If you know that the numbers form a triangle, assuming that you want to have a vector of vectors of numbers, you'd do
1 2 3 4 5 6 7 8 9 10 11
|
fstream file("myfilename");//open the file
vector<vector<int> > contents;
for(int line = 1; !file.fail(); line++) {//while you can read from the file.. (used a for loop to count the lines)
vector<int> line_contents;
for(int num = 0; num < line; num++) {//there are n numbers on the nth line
int val;
file >> val;//read a number
line_contents.push_back(val);//save it
}
contents.push_back(line_contents);//save the line
}
|
Although when your file is simple like that, you can use a bit of trivial maths instead.
1 2 3 4 5 6 7
|
vector<int> contents;
int val;
while(file >> val)//while you can successfully read..
contents.push_back(val);
//now the number on line i (starting from 0) and position j (also from 0) is at
contents[i*(i+1)/2+j];
|
Operator >> (when it's argument is a number) will discard and number of white spaces or tabs or newlines until it finds a number and stop at the end of that number. If there was a word instead of a number, tho operation would fall (this is not the case with a sting argument).
Now, if you wanted to make a vector of vectors of numbers and didn't know how many numbers there would be, the algorithm would become more ugly. Even worse if not all entries had to be numbers.. (The plan is to use std::getline from <string> and std::stringstream from <sstream>. I won't get into details, as the post is getting lengthy..)
edit: I just realised the first code snippet will read one line with a single garbage number. That's because even if >> fails (due to end of file), I still push the number it (didn't) read into line_contents and then contents. What is needed is to exit the nested loops. That could be done by prefixing the push_backs with
if (!file.fail())
or simply a
goto
.