首頁>Program>source
fgets(input,sizeof(input),stdin);
if (strcmp(input, "quit") == 0){
  exit(-1);
}

如果我键入quit,它不会退出程式; 我想知道為什麼会這樣。

順便說一下 被宣佈為 input

char *input;
最新回復
  • 5月前
    1 #

    在輸入中跟蹤換行符.见老兄.測試"退出" +換行符,例如:

    fgets(input,sizeof(input),stdin);
    if(strcmp(input, "quit\n") == 0){
        exit(-1);
    }
    

    我完全錯過了最後一句话,re char *input .根据架構, input 將為4或8个位元組长.所以代碼很有效

    fgets(input, 8, stdin);
    

    這並不能反映記憶體的實際大小, input 指着.只要輸入少於八个位元組,這可能就可以了,但是如果輸入更大,則会截斷輸入.此外,下次呼叫 fgets時,您將获得其餘輸入。

    您應该给出實際大小,或者接受@JonathanLeffler的建議,然後宣告一个char陣列,例如

    char input[64];
    fgets(input, sizeof(input), stdin);
    

    char *input = malloc(N);
    fgets(input, N, stdin);
    

  • 5月前
    2 #

    函式 fgets 可能会在讀取的字元串末尾添加換行符.您必须檢查以下內容:

    size_t ln = strlen(input) - 1;
    if (input[ln] == '\n')
        input[ln] = '\0';
    

    甚至

    strtok(input, "\n");
    

  • 5月前
    3 #

    建議您將此代碼編碼為:

    if(strstr(input, "quit") != NULL){
    

    原因:這將解決人们添加額外字元(例如,文字之前或之後的空格)的問题。

  • 5月前
    4 #

    此解決方案仅需要標準庫(stdio.h)並给出相同的結果。< / p>

    for (i = 0; input[i] != '\0'; i++); /* getting the string size */
    input[i-1] = '\0'; /* removing the newline */
    

  • 5月前
    5 #

    我所做的是將換行符替換為'\ 0'null。

    while(fgets(message,80,stdin))
    {
        l=strlen(message)-1;
        if(message[l]='\n') message[l]='\0';
                else message[i+1]='\0';
    }
    

  • objective c:iOS:一般从NSObject類序列化/反序列化複雜的JSON
  • 控製台應用程式的C#箭頭键輸入