从计数错误的文件中读取数据。读取数据的最佳做法是什么?
Reading data from a file with wrong count. What's best practice for reading in data?
我有四组文本文件,每组都包含不同的单词。
noun.txt有7个单词Article.txt有5个字verb.txt有6个单词Preposition.txt有5个单词
在下面的代码中,在我的第二个for循环中,一个计数数组跟踪我在哪个文件中读取了多少单词。例如。count[0]应该是5个世界,但count[1]有8个单词,但应该是7个。我回去查看了文本文件,没有出错,它有7个单词。这是ifstream的行为问题吗?
我也被告知()不是一个好的做法。在准确读取数据方面,行业中的最佳实践是什么?换句话说,除此之外,还有什么更好的东西可以用吗!infile.of()?
#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()
的书籍都值得立即烧掉)。
读取文件的主循环应该是这样的:
for (int j = 0; infile >> elements[j].partsOfSpeach[i]; ++j){
++count[i];
}
顺便说一句,尽管该语言被称为"C++"而不是"++C",但除非你真的使用了表达式的结果,否则不要使用后增量:在大多数情况下,这并不重要,但有时确实重要,然后后增量可能比前增量慢得多。
您是否检查过以确保文本文件末尾没有任何额外的空格或换行符?您的最后一个多余"单词"可能是由于到达eof
之前的尾随字符造成的。
文件末尾可能有一行空行,看起来是"空的"。我的建议是使用如下代码:
#include <boost/algorithm/string.hpp>
#include <string>
...
std::string line;
int cnt = 0;
while(! infile.eof()) {
infile >> line;
boost::algorithm::trim(line);
if(line.size > 0)
words[filenr][cnt++] = line;
}
请注意,我强烈建议使用一个"外部"对象,它按列表类型进行索引(如Article.txt为0,Noun.txt为1),而"内部"对象是一个向量,它接受单词。您的实现是相反的,这是次优的,因为您必须在实现中的partsOfSpeech向量中携带空槽。还要注意,在您的示例中,为每个文件的字数设置"100"的硬上限是非常危险的——这可能会导致缓冲区溢出!对于实际的单词列表,最好使用std::vector,因为vector很容易自动扩展。
- C++将文本文件中的数据读取到结构数组中
- 为 Sql 服务器实现 odbc 包装器.将数据库数据读取为字符或要求驱动程序将数据转换为 C 类型
- 如何将来自文本文件的数据读取到结构的int阵列中
- 如何将不同长度的数据读取到 2D 数组中
- 从TXT文件到C 的结构向量中的数据读取
- 将sqlite原始数据读取到qbyTearray
- 如何将来自输入TXT文件的数据读取到2 C 数组中
- 使用MQQueue将数据读取到缓冲区中时麻烦
- 在 VC++ 中将类数据读取和写入二进制文件
- 将数据从数据读取器终端获取到GUI(QtCreator)
- C 将数据读取到一个结构,但它跳过了我的一个获取线,使该元素空白
- C++将二进制数据读取到结构
- c++我需要将文件中的数据读取到多维数组中,然后用一种数据类型对数组进行排序.怎样
- 对齐数据:速度取决于恒定数据读取的相对采样大小和采样频率
- 如何将文件中的数据读取到数组中
- 如何使用Visual C++应用程序的完整应用程序数据读取Minidump的应用程序数据
- 如何将csv文件数据读取到数组中
- 用C++将格式化的数值数据读取到数组中
- 正在从文件中将数据读取到结构数组中
- 将分离的数据读取到数组结构c++中