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

时间:2015-03-17 09:08:47

标签: 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 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");
}

1 个答案:

答案 0 :(得分:2)

char ch;更改为std::string word;,将infile >> ch;更改为infile >> word;,然后您就完成了。或者甚至更好地做这样的循环:

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