用c语言写输入一行字符,统计其中有多少个单词,单 之间用空格分隔开
时间: 2023-05-22 09:06:48 浏览: 59
以下是用C语言统计一个字符串中单词数量的程序:
```c
#include <stdio.h>
#include <string.h>
int main()
{
char str[100];
int word_count = 0;
int is_word = 0;
printf("请输入一行字符:\n");
fgets(str, sizeof(str), stdin);
for (int i = 0; i < strlen(str); i++)
{
if (str[i] == ' ' || str[i] == '\n' || str[i] == '\t')
{
is_word = 0;
}
else if (is_word == 0)
{
++word_count;
is_word = 1;
}
}
printf("单词总数为: %d\n", word_count);
return 0;
}
```
输入一行字符后,程序会遍历字符串中的每一个字符,当遇到空格、换行符或制表符时,将 is_word 变量设置为 0。当下一个字符是字母或数字时,就将 is_word 变量设置为 1,并且单词计数器加 1。最后输出单词的数量。
相关问题
用C语言编写输入一行字符,统计其中有多少个单词,单词之间是用空格分隔开
以下是用C语言编写输入一行字符,统计其中有多少个单词的代码:
```c
#include <stdio.h>
#include <ctype.h>
#define IN 1
#define OUT 0
int main()
{
int c, state, count;
state = OUT;
count = 0;
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. 初始化state为OUT,count为0。
4. 读入字符,如果是空格、制表符或换行符,则将state设置为OUT。
5. 如果不是空格、制表符或换行符,并且state为OUT,则将state设置为IN,并将count加1。
6. 循环读入字符,直到读到文件结尾。
7. 输出单词数。
用c语言输入一行字符,统计其中有多少个单词,单词之间用空格分隔开
好的,以下是C语言的代码实现:
```c
#include <stdio.h>
int main() {
char str[1000];
int count = 0, i;
printf("请输入一行字符:");
fgets(str, 1000, stdin); // 使用 fgets 函数读取输入的字符串
// 统计单词数量
for (i = 0; str[i] != '\0'; i++) {
if (str[i] == ' ' && str[i-1] != ' ') {
count++;
}
}
if (str[0] != '\0') { // 如果输入的字符串不为空,则单词数量应该加1
count++;
}
printf("单词数量为:%d\n", count);
return 0;
}
```
代码逻辑如下:
1. 使用 `fgets` 函数读取输入的字符串,存储在字符数组 `str` 中;
2. 使用 `for` 循环遍历字符串,每当遇到一个空格时,判断前一个字符是否是空格,如果不是,则说明遇到了一个单词,将单词数量加1;
3. 遍历完整个字符串后,如果输入的字符串不为空,则单词数量应该加1;
4. 最后输出单词数量。
注意,本代码实现中,单词的定义是以空格为分隔符,因此如果输入的字符串中有其他分隔符(如逗号、句号等),则也会被视为一个新的单词。