gpt4 book ai didi

c++ - 我正在计算文件中的字符数,但我想计算小于 5 和 6 或更大的单词数

转载 作者:行者123 更新时间:2023-11-28 03:57:46 25 4
gpt4 key购买 nike

我想这样做:一次读取文件中的单词。 (使用字符串来做到这一点)计算三件事:文件中有多少单字符单词,文件中有多少短(2 到 5 个字符)单词,以及文件中有多少长(6 个或更多字符)单词。在这里帮助

我不确定如何将文件读入字符串。我知道我必须做这样的事情,但我不明白其余的。在这里帮助

ifstream infile;
//char mystring[6];
//char mystring[20];

int main()
{
infile.open("file.txt");
if(infile.fail())
{
cout << " Error " << endl;
}

int numb_char=0;
char letter;

while(!infile.eof())
{
infile.get(letter);
cout << letter;
numb_char++;
break;
}

cout << " the number of characters is :" << numb_char << endl;
infile.close();
return 0;

最佳答案

我不太确定从哪里开始......

你的循环:

while(!infile.eof())
{
infile.get(letter);
cout << letter;
numb_char++;
break;
}

由于额外的 break;

只会执行一次

此外,这段代码看起来像是在尝试读取文件中的字符数,而不是计算 5 个字母或大于 6 个字母的单词数。

尝试这样的事情:

ifstream infile;

int main(){
infile.open("file.txt");
if(!infile.good()){
cout << " Error " << endl;
return 1;
}
int shortCount = 0;
int mediumCount = 0;
int longCount = 0;
int charCount = 0;
char letter;
while(!infile.eof()){
infile >> letter;
if(letter == ' ' || char == EOF){ // end of word or file.
if(charCount == 1)
shortCount++;
else if(charCount < 6)
mediumCount++;
else
longCount++;
charCount = 0;
}else{
charCount++;
}
}
cout << "Short Words: " << shortCount << endl;
cout << "Medium Words: " << mediumWords << endl;
cout << "Long Words: " << longWords << endl;
infile.close();
return 0;
}

关于c++ - 我正在计算文件中的字符数,但我想计算小于 5 和 6 或更大的单词数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2775602/

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