简体   繁体   English

读取 C++ 中的文件

[英]read file in C++

I am trying to read a list of words from a file in C++.我正在尝试从 C++ 中的文件中读取单词列表。 However, the last word is read twice.但是,最后一个单词被读取两次。 I cannot understand why it is so.我不明白为什么会这样。 Can someone help me out?有人可以帮我吗?

int main () {

ifstream fin, finn;
vector<string> vin;
vector<string> typo;
string word;
fin.open("F:\\coursework\\pz\\gattaca\\breathanalyzer\\file.in");
if (!fin.is_open())
    cout<<"Not open\n";
while (fin) {
    fin >> word;
    cout<<word<<endl;
    vin.push_back(word);
}
fin.close();
}

Your loop condition is off by one:您的循环条件关闭了一个:

 while (fin >> word) {
    cout<<word<<endl;
    vin.push_back(word);
 }

You need to do:你需要做:

while((fin >> word).good()) {
     vin.push_back(word);
}

Because fin >> word fails and you don't check it.因为fin >> word失败并且您不检查它。

It's not read twice.它没有读过两次。 It's simply the old value, since fin >> word fails.这只是旧值,因为fin >> word失败。 Use利用

while(fin >> word)
{
  ...
}

instead.反而。 It tries to read and stops loop if it fails.如果失败,它会尝试读取并停止循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM