int main() {
char *name;
int howMany, i;
printf("how many character do you want to enter: ");
scanf(" %d", &howMany); /*why does it stop here */
name = (char *)malloc(5 * sizeof(char));
printf("enter characters ");
gets(name);
puts(name);
return 0;
}
最佳答案
你的程序有问题:
- 你应该检查
scanf()
的返回值; - 您不应使用过时且不安全的函数
gets()
; - 您应该分配
howMany + 1
字节而不是5
。额外的字节用于空终止符; - 你应该检查
malloc()
的返回值; gets()
读取输入流中剩余的未决换行符scanf()
并停止。观察到的行为可能是这样的:- 系统会提示您输入*您要输入多少个字符:*
- 你输入一个数字后跟一个换行符
- 程序立即退出
修改后的版本:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char *name;
int howMany, i, c;
printf("how many character do you want to enter: ");
if (scanf(" %d", &howMany) == 1) {
/* read the remainder of the line, including the newline character */
while ((c = getchar()) != EOF && c != '\n')
continue;
if (howMany <= 0) {
printf("invalid number: %d\n, howMany);
return 1;
}
name = malloc(howMany + 1);
if (name == NULL) {
printf("cannot allocate %d bytes\n, howMany + 1);
return 1;
}
printf("enter characters ");
for (i = 0; i < howMany; i++) {
if ((c = getchar()) == EOF)
break;
name[i] = c;
}
name[i] = '\0';
puts(name);
}
return 0;
}
关于c - 为什么程序在 scanf 上停止...如果删除该行它可以正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41919553/