gpt4 book ai didi

c++ - 计算文件中的单词数

转载 作者:太空宇宙 更新时间:2023-11-04 15:08:57 24 4
gpt4 key购买 nike

#include <iostream>
#include <string>
#include <fstream>
#include <cstring>

using namespace std;

int hmlines(ifstream &a){
int i=0;
string line;
while (getline(a,line)){
cout << line << endl;
i++;

}
return i;

}


int hmwords(ifstream &a){

int i=0;
char c;
while ((c=a.get()) && (c!=EOF)){
if(c==' '){
i++;
}

}

return i;


}








int main()
{
int l=0;
int w=0;
string filename;
ifstream matos;
start:
cout << "give me the name of the file i wish to count lines, words and chars: ";
cin >> filename;
matos.open(filename.c_str());
if (matos.fail()){
goto start;
}
l = hmlines(matos);
matos.seekg(0, ios::beg);
w = hmwords(matos);
/*c = hmchars(matos);*/
cout << "The # of lines are :" << l << ". The # of words are : " << w ;

matos.close();



}

我试图打开的文件包含以下内容。

Twinkle, twinkle, little bat!
How I wonder what you're at!
Up above the world you fly,
Like a teatray in the sky.

我得到的输出是:

give me the name of the file i wish to count lines, words and chars: ert.txt
Twinkle, twinkle, little bat!
How I wonder what you're at!
Up above the world you fly,
Like a teatray in the sky.
The # of lines are :4. The # of words are : 0

最佳答案

int hmwords(ifstream &a){
int i;

您忘记了初始化i。那时它可以包含任何东西。

另请注意,流上的 operator>> 默认会跳过空格。您的字数统计循环需要 noskipws 修饰符。

  a >> noskipws >> c;

另一个问题是,在调用 hmlines 之后,matos 位于流的末尾。如果你想再次读取文件,你需要重置它。尝试类似的东西:

l = hmlines(matos);
matos.clear();
matos.seekg(0, ios::beg);
w = hmwords(matos);

(必须使用clear(),否则seekg无效。)

关于c++ - 计算文件中的单词数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6800836/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com