![](/img/trans.png)
[英]Using memset and memcpy correctly to initialize a character array in C++
[英]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
。 c
是char
數組的一個非常令人困惑的名稱。 此名稱通常用於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.