如何阅读单词而不是字符

  • 本文关键字:字符 何阅读 单词 c++
  • 更新时间 :
  • 英文 :


我目前正在尝试从.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 filen";
 }
 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;
}

最新更新