我想创建一个存储一些数字的文件,以后将其提取到数组中。
#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;
}
运行上面的代码片段时,我得到以下数字:
1234 1234 1234
同时
1234 5678 90
是预期的。
然后我发现(通过将每个变量引到屏幕上),当提取到“元素”时,stringstream ss不会释放其内容。
那为什么呢?我以为像cin流一样,提取之后,该流会弹出数据吗?我错过了任何极其重要的事情吗?