簡體   English   中英

試圖打破 fgets while 循環

[英]Trying to break out of fgets while loop

#include <stdio.h>
#include <string.h>

int main(){
    char c[20], result[50];
    int bool = 0, count = 0, i;
    
    while(fgets(c,20,stdin) != NULL){
        int stringSize = strlen(c);
        if(stringSize == 11){
            
            int ascii = (int)(c[i]);
            
            for(i = 0; i < stringSize; i++){
            
                if(ascii >= 'A' && ascii <= 'Z'){
                    bool = 1;
                }
            }
        }
    }
        if(bool == 1){
            count++;
            strcat(result,c);
        }
    
    printf("%d", count);
    printf("%s",result);
}

早上好,我對編程還很陌生,我已經花了很長時間在谷歌上搜索和搜索這個問題,但我似乎無法理解它。 基本上我試圖過濾一個 fgets 以便它讀取每個字符串,如果它們是大寫字母,它們是“有效的”。 但是,我什至無法讓 fgets 停止接受更多輸入。

編輯:想法是在結果中存儲每個具有 10 個大寫字母的字符串,並且一旦用戶沒有輸入 ('\0'),fgets while 循環就會中斷

如果您從標准輸入 stream 輸入字符串,那么最好通過以下方式重寫 while 循環的條件

while( fgets(c,20,stdin) != NULL && c[0] != '\n' ){

在這種情況下,如果用戶只是按下 Enter 鍵而沒有輸入字符串,那么循環將停止其迭代。

注意 fgets 可以 append 換行符 '\n' 到輸入的字符串。 你應該像這樣刪除它

c[ strcspn( c, "\n" ) ] = '\0';

然后你可以寫

size_t n = strlen( c );

if ( n == 10 )
{
    size_t i = 0;
    while ( i != n && 'A' <= c[i] && c[i] <= 'Z' ) ++i;

    bool = i == 10;
}

請注意,使用名稱bool是一個壞主意,因為這樣的名稱是在 header <stdbool.h>中作為宏引入的。

這似乎也是 if 語句

    if(bool == 1){
        count++;
        strcat(result,c);
    }

必須在 while 循環內。 並且數組結果必須初始初始化

char c[20], result[50] = { '\0' };

暫無
暫無

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

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