簡體   English   中英

C在標准輸入中計算單詞和行數的程序

[英]C Program that counts Words and Lines in Standard input

我是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;
}

我完全不參加這個節目嗎?

如果您的問題是如何解決編譯錯誤,那很簡單。 最后再添加一個閉合括號。

但是您的程序在循環中仍然只執行一次,並且僅當用戶鍵入空格,制表符或換行符時,才打印一個字符。 無論用戶鍵入什么,程序都將終止。 我懷疑那是你想要的。

我懷疑這是您的意圖:

while ((iochar = getchar ()) !=EOF)
{
    if((iochar == ' ') || (iochar == '\t') || (iochar == '\n'))
    {
        putchar(iochar);
    }
}
return 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);

那是您需要/想要的嗎?

錯誤消息是:

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;

    }

可讀性重要性的另一個例子:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM