无法读取输入文件 ifstream
我正在尝试读取一行上用两个数字格式化的输入文件,并将该行中的第一个数字存储在一个向量中,将第二个数字存储在另一个向量中。
除了实际读取文件之外,我的代码的每个部分都工作正常。
我已经把couts
放在各处,看起来当我的文件被打开时,它没有被读取,所以我的向量不断被填充,直到我耗尽内存。
这是我的代码中读取文件的部分:(
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);
}
}
其中 counter 是一个初始化为 -1 的整数,因为在输入文件的开头有一个我需要忽略的单字标题)。
我知道使用 .eof()
是不受欢迎的,但它实际上不会影响我正在做的事情。
有人发现我的代码有问题或者为什么它不能读取文件吗?
I'm trying to read an input file formatted with two numbers on a line and store the first number in the line in one vector and the second number in another vector.
Every part of my code works fine except for the actual reading of the file.
I have put couts
all over the place and it looks like while my file is being opened, it's not being read, so my vectors keep getting filled until I run out of memory.
Here's the part of my code that reads the file:
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);
}
}
(where counter is an integer initialized at -1 since there is a one-word title at the beginning of the input file that I need to ignore).
I know using .eof()
is frowned upon, but it won't actually affect what I'm doing.
Does anyone see a problem in my code or why it wouldn't be reading the file?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为什么不使用:
它更干净,因为数据和权重成对出现(也许我改变了 w 和 d)。
Why not use:
It's much cleaner since data and weight go in pairs (maybe I changed w and d).
在 while 循环中使用
.eof()
是错误的。例如,错误。
这是正确使用。
此外,C++ 常见问题解答第 15.5 节 它说“为什么我的输入似乎超出了文件末尾?”
您还需要通过执行此操作来检查您的
fstream
是否正确打开,执行
if(!inputdata)
不是正确的检查。It is wrong to use
.eof()
in a while loop. For example,Wrong.
This is the correct use.
Additionally, at the C++ FAQ, in Section 15.5 it says "Why does my input seem process past the end of a file?"
You also need to check if your
fstream
is properly open by doing this,Doing
if(!inputdata)
is not the proper check.“因为输入文件的开头有一个单字标题,我需要忽略它”
这可能有问题。尝试读取带有整数或浮点数的文本是自找麻烦。
如果这个词在单独的一行上,请尝试以下操作:
http://www.cplusplus.com/reference/iostream/istream/getline/
否则,尝试使用临时字符串读取第一个单词。\
"since there is a one-word title at the beginning of the input file that I need to ignore"
That might be problematic. Trying to read a text with ints or floats is asking for trouble.
If this word is on a seperate line, try this:
http://www.cplusplus.com/reference/iostream/istream/getline/
Else, try to read the first word with a temporary string.\