c语言编辑程序统计单词数量
时间: 2023-12-16 11:02:21 浏览: 79
以下是一个C语言编辑程序统计单词数量的例子:
```c
#include <stdio.h>
#include <ctype.h>
#define IN 1
#define OUT 0
void countWords() {
int c, nl, nw, nc, state;
state = OUT;
nl = nw = nc = 0;
while ((c = getchar()) != EOF) {
++nc;
if (isspace(c)) {
state = OUT;
if (c == '\n') {
++nl;
}
} else if (state == OUT) {
state = IN;
++nw;
}
}
printf("Lines: %d, Words: %d, Characters: %d\n", nl, nw, nc);
}
int main() {
countWords();
return 0;
}
```
该程序通过遍历输入的字符,统计行数、单词数和字符数。其中,单词数的统计是通过判断当前字符是否为空格或换行符,以及前一个字符是否为单词字符来实现的。
相关问题
使用c语言编写单词统计程序
好的,下面是一个简单的单词统计程序,使用C语言实现:
```c
#include <stdio.h>
#include <ctype.h>
#define IN 1 /* 在单词内 */
#define OUT 0 /* 在单词外 */
int main()
{
int c, state, wc;
state = OUT;
wc = 0;
while ((c = getchar()) != EOF)
{
if (isspace(c))
{
state = OUT;
}
else if (state == OUT)
{
state = IN;
++wc;
}
}
printf("单词数为%d\n", wc);
return 0;
}
```
该程序使用了一个状态变量 `state` 来表示当前字符是否在单词内,另一个变量 `wc` 记录单词的数量。程序遍历输入的字符,遇到空格等分隔符时将 `state` 设为 `OUT`,遇到非空字符时检查 `state` 是否为 `OUT`,如果是则将其设为 `IN`,并增加 `wc` 的值。最后输出 `wc` 即为单词数量。
c语言输入句子统计单词
以下是一个简单的C语言程序,可以实现输入句子并统计单词的功能:
```c
#include <stdio.h>
#include <string.h>
int main()
{
char sentence[100];
int word_count = 0;
printf("请输入一个句子:");
fgets(sentence, 100, stdin);
// 使用 strtok 函数分割句子,统计单词数
char *word = strtok(sentence, " ");
while (word != NULL) {
word_count++;
word = strtok(NULL, " ");
}
printf("该句子中共有 %d 个单词。\n", word_count);
return 0;
}
```
该程序使用了标准库函数 `fgets` 和 `strtok`,前者用于从标准输入中读入句子,后者则用于分割句子并统计单词数。具体而言,`strtok` 函数的第一个参数为需要分割的字符串,第二个参数为分割符,返回值为分割出的第一个单词的指针。每次调用 `strtok` 函数时,它会自动从上一次结束的位置开始继续分割,直到整个字符串都被分割完为止。