#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
int main()
{
ifstream inFile("test.txt");
string line;
while(getline(inFile, line))
{
istringstream meh(line);
int n;
vector<int> v;
while(meh >> n)
v.push_back(n);
}
}
My test.txt file looks like:
429384
392041
230138
099938
243324
If I try to print v[0] I get the entire sequence of numbers back (42938…3324) instead of just the first number 4. Can anyone explain why this is happening?
You probably made a mistake when you output your data.Your code stores in fact only one
int-value for each line – the whole line was stored inside v[0]. Then you wrote that whole number inside a stream and forgot to write a new line before your while-loop started to process the next line. Thus, your output was one large number.This should work the way you expected it to be. You will have a
vector<int>container inside avector<vector<int> >. The first one will store your number in a line, whereas each character will be stored individually. The latter vector simply stores the vectors for the numbers for your lines. Thechartointconversion should explain itself when you take a look at the ASCII-table.