如何打印以特定字符开头的单词数?

How do I print the number of words that begin with a certain character?

本文关键字:字符 开头 单词数 何打印 打印      更新时间:2023-10-16

这是针对介绍 c++ 类的,提示符如下:

打印以特定字符开头的单词数。让用户输入该字符。

虽然,我不知道该怎么做。

我是否使用解析字符串?我尝试了这个,因为他们检查字符串数据类型,但我不断收到错误,所以我把它拿出来并更改为字符。我想学习如何执行"total_num"(以用户选择的字母开头的单词总数(,并且还需要一些有关 for 循环的帮助。

所需输出的示例

用户输入:输出
:"找到 1270 个以 a 开头的单词">

用户输入:E 输出:"找到 16 个以 E
开头的单词">

用户输入:#
输出:"找到 0 个以 # 开头的单词">

(我想我把这部分记下来了,不按字母顺序(

数据来自一个名为dict.txt的文件,它是一个包含许多单词的列表。

以下是它包含内容的一小部分示例:

D
d
D.A.
dab
dabble
dachshund
dad
daddy
daffodil
dagger
daily
daintily
dainty
dairy
dairy cattle
dairy farm
daisy
dally
Dalmatian
dam
damage
damages
damaging
dame

我的程序:

#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
const int NUM_WORD = 21880;//amount of words in file
struct dictionary { string word; };
void load_file(dictionary blank_array[])
{
ifstream data_store;
data_store.open("dict.txt");
if (!data_store)
{
cout << "could not open file" << endl;
exit(0);
}
}
int main()
{
dictionary file_array[NUM_WORD];
char user_input;
int total_num = 0;
load_file(file_array);
cout << "Enter a character" << endl;
cin >> user_input;
if (!isalpha(user_input))
{
cout << "Found 0 that begin with " << user_input << endl;
return 0;
}
for (int counter = 0; counter< NUM_WORD; counter++)
{
if (toupper(user_input) == toupper(file_array[counter].word[0]));
//toupper is used to make a case insensitive search
{
cout << "Found " << total_num << " that begin                                   with " << user_input << endl;
//total_num needs to be the total number of words that start with that letter
}
}
}

您可以做一些事情来简化您的生活,例如按照评论的建议使用vector

让我们看看你的 for 循环。存在一些明显的语法问题。

int main()
{
dictionary file_array[NUM_WORD];
char user_input;
int total_num = 0;
load_file(file_array);
cout << "Enter a character" << endl;
cin>>user_input;
if(!isalpha(user_input))
{
cout << "Found 0 that begin with " << user_input << endl;
return 0;
}
for(int counter = 0;counter< NUM_WORD; counter++)
{
if (toupper(user_input) == toupper(file_array[counter].word[0]));
//                                                             ^no semi-colon here!
//toupper is used to make a case insensitive search
{
cout<< "Found " << total_num << " that begin  with "<<
user_input       << endl;
//total_num needs to be the total number of words that start with that letter
}
}//<<< needed to end the for loop
}

让我们正确设置for循环。您希望对循环中的匹配项进行计数,然后在完成循环时报告。

int total_num = 0;
//get character and file
for(int counter = 0;counter< NUM_WORD; counter++)
{
if (toupper(user_input) == toupper(file_array[counter].word[0]))
^^^no semi-colon here!
{
++total_num;
}
}
cout<< "Found " << total_num << " that begin  with "<<                                                                                          user_input       << endl;