从文件输入中计算行数
Counting lines from a file input?
下面的代码应该计数:从文本文件中读取的行,字符和单词。
输入文本文件:
This is a line.
This is another one.
期望的输出是:
Words: 8
Chars: 36
Lines: 2
但是,单词计数显示为0,如果我更改它,那么行和字符显示为0,单词计数是正确的。我得到这个:
Words: 0
Chars: 36
Lines: 2
这是我的代码:
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
ifstream inFile;
string fileName;
cout << "Please enter the file name " << endl;
getline(cin,fileName);
inFile.open(fileName.c_str());
string line;
string chars;
int number_of_lines = 0;
int number_of_chars = 0;
while( getline(inFile, line) )
{
number_of_lines++;
number_of_chars += line.length();
}
string words;
int number_of_words = 0;
while (inFile >> words)
{
number_of_words++;
}
cout << "Words: " << number_of_words <<"" << endl;
cout << "Chars: " << number_of_chars <<"" << endl;
cout << "Lines: " << number_of_lines <<"" << endl;
return 0;
}
请指教。
由于评论通常不被寻求答案的人阅读…
while( getline(inFile, line) )
读取整个文件。当它完成后,inFile
的读取位置被设置为文件的末尾,因此单词计数循环
while (inFile >> words)
从文件末尾开始读取,但一无所获。要使其正确执行,对代码的最小更改是在计算单词之前使用seekg倒带文件。
inFile.seekg (0, inFile.beg);
while (inFile >> words)
将读取位置定位到相对于文件开头的文件偏移量0(由inFile.beg
指定),然后读取整个文件以计数单词。
虽然这可以工作,但它需要对文件进行两次完整的读取,这可能相当慢。crashmstr在评论中建议了一个更好的选择,并由simplicis veritatis实现,作为另一个答案,需要对文件进行一次读取以获取和计数行,然后在RAM中对每行进行迭代以计数单词数。
这具有相同的总迭代次数,所有内容都必须逐一计数,但是从内存中的缓冲区读取比从磁盘读取更可取,因为从内存中读取要快得多,数量级,访问和响应时间
这里有一个可能的实现(未测试)用作基准:
int main(){
// print prompt message and read input
cout << "Please enter the file name " << endl;
string fileName;
getline(cin,fileName);
// create an input stream and attach it to the file to read
ifstream inFile;
inFile.open(fileName.c_str());
// define counters
string line;
string chars;
int number_of_lines = 0;
int number_of_chars = 0;
vector<string> all_words;
do{
getline(inFile, line);
// count lines
number_of_lines++;
// count words
// separates the line into individual words, uses white space as separator
stringstream ss(line);
string word;
while(ss >> word){
all_words.push_back(word);
}
}while(!inFile.eof())
// count chars
// length of each word
for (int i = 0; i < all_words.size(); ++i){
number_of_chars += all_words[i].length();
}
// print result
cout << "Words: " << all_words.size() <<"" << endl;
cout << "Chars: " << number_of_chars <<"" << endl;
cout << "Lines: " << number_of_lines <<"" << endl;
return 0;
}
相关文章:
- 如何计算文件中的"columns"数?
- 如何计算文件中的生物数量?
- 你如何计算文件中的字符
- 计算文件中不使用 getline() 的行数
- 我的逻辑有什么问题?尝试计算文件中包含特定字符的单词数
- 如何使用Boost计算文件的MD5
- C++:计算文件中ASCII字符的频率
- 计算文件中字符的频率.C++
- C++ 计算文件中两个单词之间的单词
- 创建一个读取的程序计算C 文件中的行数
- 计算文件夹C++窗口中的目录数
- C++ 使用类来计算文件中的行数
- 逐行计算文件:EOF 重复最后一个数字(不能使用中断)
- 你如何计算文件中的整数数量?(C++)
- 计算文件的熵
- 如何计算文件中的字符、行和单词
- 计算文件中的整数并复制到动态数组
- 计算文件C++中每行的整数数量
- 如何计算文件的增量,即更改的文件部分
- 如何在C或c++中计算文件的哈希值