簡體   English   中英

計算小寫字母,直到輸入為字符串

[英]Count lowercase letters till the input is string

我用C編寫了一個短代碼,該代碼計算小寫字母(僅包括字母),當我輸入數字或其他內容時它將停止工作。 這是代碼:

char letter;
int num=0;
do
    if(islower(letter = getchar()))
       num++;
while(isalpha(letter));
printf("%d", num);
return 0;

我的問題是它不能正常工作(僅打印“ 1”作為結果)。 當下一個字符不是字母時,必須停止它。 不確定該部分是否正確。

知道我錯了什么嗎? 謝謝。

怎么了

char letter;
int num=0;
while (isalpha(letter = getchar())) {
    if (islower(letter)) num++;
}
printf("%d", num);
return 0;

當下一個字符不是字母時,必須停止它。

可以緩沖鍵盤輸入-在按下Enter鍵之前不進行處理

結果僅打印“ 1”

您能寫一些在控制台輸入導致“ 1”輸出的示例嗎?

問題在於,輸入單個字符后,對getchar()的后續調用將返回換行符,因為返回鍵中的'\\n'已被緩沖。 因此,

 do
    if (islower(letter = getchar()))
        num++;
 while (isalpha(letter));

可以,但是程序顯示“ 1”,因為在處理換行符時, islower()調用返回false。

要解決此問題,請使用while循環吃掉多余的換行符。 您可以這樣做:

do {
    while ((letter = getchar()) == '\n')
        ;

    if (islower(letter))
        num++;
} while (isalpha(letter));

暫無
暫無

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

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