簡體   English   中英

如何使用fgets讀取和計算字符

[英]How to use fgets to read and count charaters

假設我要計算stdin中的字符abcdef...。

碼:

int string[100] = "";
int a_count = 0...

while(fgets(string, sizeof(string), stdin))
{
    for(int y = 0; y < 100; y ++)
    {
        if(string[y] == 'a') a_count++;
        if(string[y] == 'b') b_count++;
           ...and so on...
    }
    //here I reset the string to empty.
}

上面的代碼無法正常工作(比預期的要多),我在哪里犯了邏輯錯誤?

您需要在實際字符串的末尾終止for循環,而不是遍歷整個數組。 您需要在看到NUL終止符時停止操作。

while (fgets(string, sizeof(string), stdin) != NULL)
{
    for(int y = 0; string[y] != 0; y ++)
    {
        if(string[y] == 'a') a_count++;
        if(string[y] == 'b') b_count++;
           ...and so on...
    }
}

處理完字符串后,無需將其設置為“空”。 以后的fgets()調用將覆蓋它,這很好。

另外,您可能會想出更好的方法來編寫實際的計數器,但這不是您要問的問題。

問題在於您不僅要計算字符串中的字符,還要計算整個緩沖區中的所有垃圾 你不想那樣做。 循環直到僅字符串末尾。

此外,還可以替代的巨大鏈接if有一個簡單的表/數組查找,像這樣:

int counts[1 << CHAR_BIT] = { 0 };

while (fgets(buf, sizeof(buf), stdin) != NULL) {
    const char *p = buf;
    while (*p != 0) {
        counts[*p++]++;
    }
}

然后,最后,您可以按以下方式檢索特定字符的計數:

printf("'a': %d occurrences\n", counts['a']);

等等

暫無
暫無

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

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