I want to create a file which stores some digits, later to be extracted into an array.
#include <vector>
#include <fstream>
#include <iostream>
#include <stringstream>
//for setw()
#include <iomanip>
std::vector<int> getData()
{
using namespace std;
//For the sake of this question simplicity
//I won't validate the data
//And the text file will contain these 10 digits:
//1234567890
ifstream in_file("altnum.txt");
//The vector which holds the results extracted from in_file
vector<int> out;
//It looks like C++ doesn't support extracting data
//from file to stringstream directly
//So i have to use a string as a middleman
stringstream ss;
string str;
//Extract digits from the file until there's no more
while (!in_file.eof())
{
/*
Here, every block of 4 digits is read
and then stored as one independent element
*/
int element;
in_file >> setw(4) >> str;
cout<<str<<"\n";
ss << str;
cout<<ss.str()<<"\n";
ss >> element;
cout<<element<<"\n";
out.push_back(element);
}
//Tell me, program, what have you got for my array?
for (auto &o : out)
cout << o << ' ';
in_file.close();
return out;
}
When i run the snippet of code above, i get the following numbers:
1234 1234 1234
while
1234 5678 90
is expected.
And then i found out (by cout-ing each variable to the screen) that the stringstream ss does not release its content when extracted to 'element'
But why is that? I thought that like cin stream, after the extraction, the stream would pop data out of it? Did i miss anything extremely important?