使用循环和选择语句,从键盘上接受一句话,计算一共有几个字符和单词。单词间用空格或者标点符号分隔,最终输出结果,要求有功能菜单,含退出功能
时间: 2023-05-21 10:06:07 浏览: 50
非常感谢你的问题,以下是C知道的回答:
可以使用循环和选择语句,从键盘接收一句话,计算字符数和单词数。可以考虑使用以下步骤:
1.提示用户输入一句话。
2.使用fgets()函数从标准输入stdin接收输入的句子。
3.使用strlen()函数计算输入的句子的字符数,包括空格和标点符号。
4.使用strtok()函数将输入的句子分解为单个单词,并使用计数器计算单词数。
5.输出字符数和单词数。
以下是一个参考代码:
```c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_LEN 100
int main() {
char sentence[MAX_LEN];
char *word;
int count_char, count_word;
int choice;
while (1) {
printf("请输入一句话:");
fgets(sentence, MAX_LEN, stdin);
sentence[strlen(sentence)-1] = '\0';
count_char = strlen(sentence);
count_word = 0;
word = strtok(sentence, " ,.!?");
while (word != NULL) {
count_word++;
word = strtok(NULL, " ,.!?");
}
printf("输入的句子中有 %d 个字符和 %d 个单词。\n", count_char, count_word);
printf("请选择:1.继续 2.退出\n");
scanf("%d", &choice);
getchar();
if (choice == 2) {
break;
}
}
return 0;
}
```
请注意,这只是一个示例,并且可能需要一些修改以适合您的具体需求。