gpt4 book ai didi

c++ - 如何阅读单词而不是字符?

转载 作者:行者123 更新时间:2023-11-28 02:30:41 25 4
gpt4 key购买 nike

我目前正在尝试从 .txt 文档中读取一堆单词,但只能设法读取字符并显示它们。我想做同样的事情,但要用完整的单词。

我的代码:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{

ifstream infile("banned.txt");
if (!infile)

{

cout << "ERROR: ";
cout << "Can't open input file\n";

}

infile >> noskipws;
while (!infile.eof())
{
char ch;
infile >> ch;

// Useful to check that the read isn't the end of file
// - this stops an extra character being output at the end of the loop
if (!infile.eof())
{
cout << ch << endl;
}
}
system("pause");
}

最佳答案

char ch; 更改为 std::string word; 并将 infile >> ch; 更改为 infile >> word; 就大功告成了。或者更好的做法是像这样循环:

std::string word;
while (infile >> word)
{
cout << word << endl;
}

关于c++ - 如何阅读单词而不是字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29095079/

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