您的 a 声明指定了一个 20 个字符的数组:a[0]
到a[19]
. a[20]
超出范围:a[20]=getchar();
。
getchar
返回int
。这样做是为了将非字符EOF
值与有效字符值区分开来。任何正返回值都是一个字符。任何负值都是错误...但是您需要将返回值存储在 an 中int
并检查该 int 是否有负值以处理错误!
int c = getchar();
if (c < 0) {
fputs("Read error while reading from stdin", stderr);
return EXIT_FAILURE;
}
a[19] = c; /* Don't rely on this being a string, since a string is a sequence of
* characters ending at the first '\0' and this doesn't have a '\0'.
* Hence, it isn't a string. Don't pass it to any str* functions! */
同样,您可能应该处理来自 scanf 的错误:
switch (scanf("%d", &b)) {
case 1: /* excellent! 1 means that one variable was successfully assigned a value. */
break;
case 0: fputs("Unexpected input while reading from stdin; "
"The \"%d\" format specifier corresponds to decimal digits.", stderr);
return EXIT_FAILURE;
default: fputs("Read error while reading from stdin", stderr);
return EXIT_FAILURE;
}
if (a=="ilangeeran")
是胡说八道。你在看哪本书?