簡體   English   中英

C 循環無法正確運行循環的所有方面。 僅在循環的特定部分循環

[英]C loop doesn't properly run all aspects of the loop. Loops only on a certain part of the loop

所以我想無限循環並以用戶字符串作為輸入,然后對其進行排序。 我想不斷輸入,直到用戶輸入“退出”。 這部分代碼有效。 但是,它不會正確地無限循環。 (這也是嚴格的 C 語言)。

它應該要求用戶輸入一個字符串,對其進行排序,打印它,要求用戶輸入一個字符串,對其進行排序等等。但是,它的作用是要求用戶輸入一個字符串,對其進行排序,打印它,然后打印它,打印它,打印它等等。這里有什么問題? 謝謝。

int main(){
    //Allocate a 100 character long array in the heap which will be passed and altered in place and outputted.
    //I'm not fully sure how to allocate dynamically the appropriate amount of space for strings without creating a whole class for it.
    //But seeing as this is c and not c++ then I'm not sure. Cause I need to have a length of how long the input is, but I need the memory allocated
    //to store the string ti find the length of.
    char* input = (char*)malloc(100);
    //Scanf allows input for any characters including white space.
    while(1){
        printf("Enter an input string: ");
        scanf("%[^\n]", input);

        int len = strlen(input);
        //Checks for exit condition. Input string being 'EXIT'
        if(len == 4 && input[0] == 'E' && input[1] == 'X' && input[2] == 'I' && input[3] == 'T'){
            break;
        }
        else{
        //Function calls
            remove_duplicates(input);
            sort(input);

            printf("\"%s\"\n", input);
        }
    }
    free(input);
    input = NULL;

    return 0;
}

scanf的許多格式說明符跳過前導 while-space(如換行符),但不是"%["

因此,在第一個輸入中按Enter添加的換行符將是下一次調用scanf將讀取的第一件事。 並且使用您的格式,換行符(或實際上是任何空格)將告訴scanf停止讀取,這意味着將不再讀取任何內容。 一遍又一遍地。

我寧願建議您使用fgets來讀取行,因為它還包括自動緩沖區溢出保護(如果您傳遞了正確的緩沖區大小)。

如果您擔心fgets添加的換行符,可以使用strcspn function 輕松刪除。

所以最好做類似的事情

char input[100];
while (fgets(input, sizeof input, stdin) != NULL)
{
    input[strcspn(input, "\n")] = 0;  // Remove possible trailing newline

    if (strcmp(input, "EXIT") == 0)
        break;  // Exit
    else
    {
        // Rest of code
    }
}

暫無
暫無

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

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