我正在尝试读取一个输入文件,该文件的格式为一行中有两个数字,并将该行中的第一个数字存储在一个 vector 中,将第二个数字存储在另一个 vector 中。
除了实际读取文件之外,我的代码的每个部分都工作正常。
我在各处都放置了 couts
,看起来当我的文件被打开时,它没有被读取,所以我的 vector 不断被填充,直到我用完内存。
这是我读取文件的代码部分:
cout << "Input Filename: ";
cin >> input;
//open input file
inputdata.open(input.c_str());
if(!inputdata){
cerr << "Error: Unable to open file!" << endl;
}
while(!inputdata.eof()){
counter++;
hold = 0;
if(counter > 0){
inputdata >> hold;
//cout << hold << endl;
if(counter%2 != 0)
data.push_back(hold);
else
weight.push_back(hold);
}
}
(其中计数器是一个初始化为 -1 的整数,因为在输入文件的开头有一个单词标题我需要忽略)。
我知道使用 .eof()
是不受欢迎的,但它实际上不会影响我正在做的事情。
有没有人发现我的代码有问题或者为什么它不读取文件?
最佳答案
为什么不使用:
std::string firstword;
inputdata >> firstword; // or std::getline(inputdate, firstword);
while (inputdata >> w >> d)
{
weight.push_back(w);
data.push_back(d);
}
由于数据和权重是成对出现的(也许我更改了 w 和 d),因此更加简洁。
关于c++ - 无法读取输入文件 ifstream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6790821/