我正在编写一个程序,它从不同的文件中读取数据,这些文件作为输入字符串给出,并将它们存储到 vector 的 vector 中。我无法调试读取不同文件的循环的问题。我已经关闭了 ifstream 对象,使用空函数清除了字符串...但是当我输入第二个文件名时它仍然终止。
我正在复制代码供您阅读。它是由另一个函数调用的函数。 Transposectr 转置矩阵。
代码:
vector<vector<float> > store1,store2;
ifstream bb;
string my_string;
float carrier;
vector<float> buffer;
cout<<"enter the file name"<<endl;
getline(cin,my_string);
while (my_string!="end")
{
bb.open(my_string.c_str());
while (!bb.eof())
{
bb >> carrier;
if (bb.peek() == '\n' || bb.eof() )
{
buffer.push_back(carrier);
store1.push_back(buffer);
buffer.clear();
}
else
{
buffer.push_back(carrier);
}
}
bb.close();
buffer.clear();
transposectr1(store1);
storex.push_back(store1[1]);
storey.push_back(store1[0]);
store1.clear();
my_string.empty();
cout<<"done reading the file"<<endl;
cout<<"enter the file name"<<endl;
getline(cin,my_string);
}
最佳答案
我真的不清楚你想做什么。但在使用 istream 时,我有一个黄金法则:
切勿使用eof() 函数!
它几乎肯定不会按照您的想法行事。相反,您应该测试读取操作是否成功。
int x;
while( in >> x ) {
// I read something successfully
}
您可能也想避免使用 peek()。尝试根据此建议重写您的代码。
关于c++ - 从文件中读取数据,文件名作为输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/992469/