【发布时间】:2013-08-12 20:22:19
【问题描述】:
我有四组文本文件,每组都包含不同的单词。
noun.txt 有 7 个单词 Article.txt 有 5 个字 verb.txt 有 6 个单词和 Preposition.txt 有 5 个单词
在下面的代码中,在我的第二个 for 循环中,一个计数数组跟踪我读入了多少单词以及从哪个文件中读取。例如。 count[0] 应该是 5 个世界,但 count[1] 有 8 个单词但应该是 7 个。我回去检查文本文件,我没有弄错,它有 7 个单词。这是 ifstream 行为的问题吗?
我还被告知 eof() 不是好习惯。在准确读取数据方面,行业中的最佳实践是什么?换句话说,除了 !infile.eof() 之外,我还能使用更好的东西吗?
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <cctype>
#include <array> // std::array
using namespace std;
const int MAX_WORDS = 100;
class Cwords{
public:
std::array<string,4> partsOfSpeech;
};
int main()
{
Cwords elements[MAX_WORDS];
int count[4] = {0,0,0,0};
ifstream infile;
string file[4] = {"Article.txt",
"Noun.txt",
"Preposition.txt",
"verb.txt"};
for(int i = 0; i < 4; i++){
infile.open(file[i]);
if(!infile.is_open()){
cout << "ERROR: Unable to open file!\n";
system("PAUSE");
exit(1);
}
for(int j = 0;!infile.eof();j++){
infile >> elements[j].partsOfSpeech[i];
count[i]++;
}
infile.close();
}
ofstream outfile;
outfile.open("paper.txt");
if(!outfile.is_open()){
cout << "ERROR: Unable to open or create file.\n";
system("PAUSE");
exit(1);
}
outfile.close();
system("PAUSE");
return 0;
}
【问题讨论】:
-
不要使用
.eof()。这里出现的大多数关于读取文件的问题都是滥用.eof()。谁在到处告诉人们使用.eof()?当>>运算符失败时,任何 C++ 教科书和教程都会告诉你停止阅读;即while (file >> variable) { ... do something ... }。 -
@DanielKO 好的,我采纳了你的建议,它有效。我将我的 for 循环转换为 int j = 0; while(infile >> ...) {}.
-
@DanielKO 哦,回答你的问题,很多大学似乎都在推广 .eof()
-
@AmberRoxanna 让你想要求退款,不是吗?