0

我是 C 编程的新手,目前正在尝试自学如何创建一个 C 程序,该程序可以计算输入流中的单词和行数并将两个总数打印到标准输出。

我实际上想做的是让程序计算行数,并根据我觉得我不在的单词的定义来计算单词的数量。

我希望单词排除空格、制表符、换行符、连字符或冒号。让程序以小数形式输出结果(单词和行)。

#include<stdio.h>

int main()
{
    int iochar;
    int words;
    int lines;

    printf("Enter something here:\n\n");

    while ((iochar = getchar ()) !=EOF)
    {
        if((iochar == ' ') || (iochar == '\t') || (iochar == '\n'))

        putchar(iochar);
    }

    return 0;
}

我完全不参加这个计划了吗?

4

3 回答 3

1

If your question is how to fix the compile error, that's simple. Add one more closing brace at the end.

But your program will still do only one pass through the loop and will print only one character if and only if the user types a space, tab or newline. No matter what the user types, the program will then terminate. I doubt that's what you wanted.

I suspect this is what you intended:

while ((iochar = getchar ()) !=EOF)
{
    if((iochar == ' ') || (iochar == '\t') || (iochar == '\n'))
    {
        putchar(iochar);
    }
}
return 0;
于 2012-09-25T22:29:04.127 回答
0

在你的“我试图让你的数字在 8 列字段中正确对齐......”之后,我无法理解你想说什么:(

int words = 0;
int lines = 0;
char buffer[1024];
while(fgets(buffer, sizeof buffer, stdin))
{
    lines++;
    if(buffer[0] == '\n')
        continue;
    char *tmp = buffer-1;
    while(tmp = strchr(tmp+1, ' '))
        words++;
    words++; /* count last word before \0*/
}

printf("lines: %d, words: %d\n", lines, words);

那是你需要/想要的吗?

于 2012-09-25T22:09:15.240 回答
0

错误信息是:

Test.c:20:1:错误:输入末尾的预期声明或语句

它无法编译,因为您缺少}.

如果你正确缩进你的代码,像这样,你会发现你的错误:

#include<stdio.h>

int main() {

   int iochar;
   int words;
   int lines;

    printf("Enter something here:\n\n");

    while ((iochar = getchar ()) !=EOF)
    {
       if((iochar==' ')||(iochar=='\t')||(iochar=='\n'))
       {
       putchar(iochar);
       iochar = getchar();
       }
       return 0;

    }

可读性重要性的另一个例子:)

于 2012-09-25T22:17:02.347 回答