我目前正在尝试从.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");
}
答案 0 :(得分:2)
将char ch;
更改为std::string word;
,将infile >> ch;
更改为infile >> word;
,然后您就完成了。或者甚至更好地做这样的循环:
std::string word;
while (infile >> word)
{
cout << word << endl;
}