C语言 编写程序,在随机输入的一行字符中统计其中有多少个单词
时间: 2024-03-23 15:38:14 浏览: 25
好的,我可以帮你解决这个问题。以下是一个统计单词数量的C语言程序示例:
```c
#include <stdio.h>
int main() {
char str[100];
int words = 0, i;
printf("请输入一行字符:\n");
fgets(str, 100, stdin);
i = 0;
while (str[i] != '\0') {
// 如果当前字符是字母,则跳过
while (str[i] >= 'a' && str[i]<= 'z' || str[i] >= 'A' && str[i] <= 'Z') {
i++;
}
// 单词数量加一
words++;
// 跳过空格和非字母字符
while (str[i] == ' ' || str[i] == '\n' || str[i] == '\t' || str[i] == '\r') {
i++;
}
}
printf("该行字符包含 %d 个单词。\n", words);
return 0;
}
```
这个程序使用循环遍历输入的字符串,每当遇到一个非字母字符(如空格、换行符、制表符等)时,就将单词数量加一。最后输出统计结果。希望能对你有所帮助!
相关问题
C语言 编写程序,在随机输入的一行字符中统计其中有多少个单词
好的,这道题目之前已经回答过了。以下是用C语言实现的程序:
```c
#include <stdio.h>
#include <ctype.h>
#define IN 1 /* 在单词内 */
#define OUT 0 /* 在单词外 */
int main()
{
int c, state = OUT, count = 0;
printf("请输入一行字符:\n");
while ((c = getchar()) != EOF)
{
if (isspace(c))
state = OUT;
else if (state == OUT)
{
state = IN;
count++;
}
}
printf("单词数为:%d\n", count);
return 0;
}
```
如果你有其他问题,可以继续问我。
用c语言编写程序,使输入一行字符,统计其中有多少个单词,单词之间是用空格分隔开
以下是用C语言编写程序,实现输入一行字符,统计其中有多少个单词,单词之间用空格分隔开的代码:
```c
#include <stdio.h>
#include <ctype.h>
#define IN 1
#define OUT 0
int main() {
int c, state = OUT, count = 0;
printf("请输入一行字符,单词之间用一个空格分隔开:\n");
while ((c = getchar()) != EOF) {
if (isspace(c)) {
state = OUT;
} else if (state == OUT) {
state = IN;
count++;
}
}
printf("该行字符有%d个单词。\n", count);
return 0;
}
```
代码思路:
1. 定义两个常量IN和OUT,分别表示在单词内和单词外。
2. 定义变量c、state和count,其中c表示当前读入的字符,state表示当前状态,count表示单词个数。
3. 通过getchar()函数逐个读入字符,如果读到空格、制表符或换行符,就将state设置为OUT,表示当前不在单词内;如果读到非空格字符且state为OUT,就将state设置为IN,表示当前进入了一个新单词,同时将count加1。
4. 最后输出单词个数。