gpt4 book ai didi

c++ - 在 C++ 中逐字读取文件

转载 作者:IT老高 更新时间:2023-10-28 22:15:50 27 4
gpt4 key购买 nike

这个函数应该逐字读取文件它确实有效,直到最后一个字,运行停止

void readFile(  )
{
ifstream file;
file.open ("program.txt");
string word;
char x ;
word.clear();

while ( ! file.eof() )
{
x = file.get();

while ( x != ' ' )
{
word = word + x;
x = file.get();
}

cout<< word <<endl;
word.clear();

}
}

有人知道问题出在哪里以及如何解决吗?

最佳答案

首先,不要循环 while (!eof()),它不会像你期望的那样工作,因为 eofbit 不会被设置,直到由于文件结束导致读取失败。

其次,普通输入操作符>>在空格上分隔,因此可用于读取“单词”:

std::string word;
while (file >> word)
{
...
}

关于c++ - 在 C++ 中逐字读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20372661/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com