簡體   English   中英

使用memset時,數組未正確重置

[英]Array is not reseting correctly, when using memset

當我從stdin中取出一個大到c的值時,重置不符合預期。 將重新提示用戶輸入代碼,但在輸入需要輸入的附加新行之后,將顯示長度檢查失敗。

void clear(void) {    
    while (getchar() != '\n')
        ;
}

int add_flight(code_t codes[], int lf) {
    char c[MAX_CODE_LEN + 1];
    int s = 0;
    while (s == 0) {
        printf("Enter code>\n");
        if (fgets(c, sizeof c, stdin)) {
            printf("%s", c);
            if ('\n' == c[0]) {
                printf("Invalid input\n");
            } else if (c[sizeof c - 1] == '\0' && c[sizeof c - 2] != '\n') {
                clear();
                printf("Invalid input\n");
                memset(c, 0, sizeof c);
            } else {
                strcpy(codes[lf].id, c);
                s = 1;
                break;
            }
        }
    }
    return 0;
}

任何幫助將不勝感激。

您的代碼中存在幾個問題:

  • clear函數不測試文件結尾,如果標准輸入在沒有尾隨換行符的情況下關閉則會導致無限循環,就像重定向空文件中的輸入一樣。
  • 對超長輸入行的測試不正確:如果輸入未填充數組,則數組的最后一個字符是未定義的。 在剝離尾部換行符后,您應該測試strlen(c) == sizeof(c) - 1
  • cchar數組的一個非常令人困惑的名稱。 此名稱通常用於int以接收字節值。 將數組命名為buf以提高可讀性。
  • 當你要在數組中讀取一個新行時, memset是無用的。
  • 缺少code_t的定義。 如果其id成員數組的大小至少不是MAX_CODE_LEN + 1 ,則行為將是未定義的。
  • 此外,您將尾隨換行符復制到codes[lf].id ,這可能是不正確的。
  • 如果id被定義為保存MAX_CODE_LEN字符,即char id[MAX_CODE_LEN + 1]; 對於額外的空終止符, buf應該有一個額外的字節用於由用戶鍵入的換行符,因此char buf[MAX_CODE_LEN + 2];

這是一個修改版本:

int clear(void) {
    int c;   
    while ((c = getchar()) != EOF && c != '\n')
        continue;
    return c;
}

int add_flight(code_t codes[], int lf) {
    char buf[MAX_CODE_LEN + 2];

    for (;;) {
        printf("Enter code>\n");
        if (fgets(buf, sizeof buf, stdin)) {
            printf("%s", buf);
            /* remove the trailing newline if present */
            size_t len = strlen(buf);
            if (len > 0 && buf[len - 1] == '\n')
                buf[--len] = '\0';
            if (len == sizeof(buf) - 1) {
                /* line too long: consume the rest of the input line */
                printf("Invalid input\n");
                if (clear() == EOF)
                    break;
            } else if (len == 0) {
                /* empty line */
                printf("Invalid input\n");
            } else {
                strcpy(codes[lf].id, buf);
                return 1;  // return success
            }
        } else {
            break;
        }
    }
    return 0;  // premature end of file: return failure
}

暫無
暫無

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

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