C++ 从文件输入中计算行数?
下面的代码应该计数:从文本文件中读取的行、字符和单词 输入文本文件:C++ 从文件输入中计算行数?,c++,C++,下面的代码应该计数:从文本文件中读取的行、字符和单词 输入文本文件: 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<
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;
}
#包括
#包括
#包括
使用名称空间std;
int main()
{
河流充填;
字符串文件名;
(用词)
{
单词数++;
}
cout这里有一个可能的实现(未测试)用作基准:
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;
}
intmain(){
//打印提示消息并读取输入
cout(单词){
所有单词。推回(单词);
}
}而(!infle.eof())
//查尔斯伯爵
//每个单词的长度
for(int i=0;i cout而且,由于寻求答案的人经常看不到评论
while( getline(inFile, line) )
读取整个文件。完成后,infle
的读取位置设置为文件的结尾,因此字数循环
while (inFile >> words)
从文件末尾开始读取,但未找到任何内容。要使代码正确执行,对代码的最小更改是在计算字数之前使用“倒带”文件
inFile.seekg (0, inFile.beg);
while (inFile >> words)
将读取位置定位为相对于文件开头的文件偏移量0(由infle.beg
指定),然后读取文件以计算字数
inFile.seekg (0, inFile.beg);
while (inFile >> words)
虽然这样做有效,但它需要对文件进行两次完整的读取,这可能会非常慢。crashmstr在评论中建议了一个更好的选项,并由simplicis veritatis实现,作为另一个答案,该选项需要读取一次文件以获取并计算行数,然后通过RAM中的每行进行迭代以计算字数
这具有相同的总迭代次数,所有内容都必须逐个计数,但从内存中的缓冲区读取比从磁盘读取更可取,因为其速度、数量级、访问和响应时间要快得多。while(getline(infle,line))
吃掉整个文件。在之前倒带或关闭并重新打开(填充>>单词)你需要1个文件。关闭和重新打开文件2。使用<代码> StrasStult找到每行中有多少个单词。使用<代码> StrugSuth从每一行获得单词可能更有用。从长远来看,一个教现代正确C++的亵渎者!@ BMG我不是真性别歧视或性别偏见,而是。问“哪一个更“漂亮”?“是典型的女性行为,只是混淆了你的主要问题。很抱歉这么说。@simplicisveritatis同意。因此,这个答案是正确的。