这是我坚持的程序的一部分。当我输入5.5时,我的程序将运行两次,但是我希望它读作5.5,而不是5,然后再读5。我知道我需要添加%f (因此添加了一个浮点输入),但是,我不确定在对char执行scanf之后如何实现它。我只想让程序接受整数,这样它就不能接受5.5作为值。它在do-while循环中。任何帮助都将非常感谢,请详细解释,因为我对编程仍然是一种新手。
int amount;
float input;
do{
printf("\nPlease enter integer:");
if(scanf("%d", &amount)!= 1){
//if reads a character or symbol asks to try again
printf("\nEnter numbers only!\n");
getchar();
}
..。
发布于 2020-04-29 03:54:38
使用带有整数格式(%d
)的scanf
,然后输入非整数值,这将导致灾难(或者至少是您的程序无法工作)。
使用scanf并仅键入整数,或者读取字符串并将字符串转换为整数。
do {
char* line = NULL;
size_t sz = 0;
printf("\nPlease enter integer:");
getline(&line, &sz, stdin);
if (line == NULL) {
// TODO error handling
// Can also check the getline() -1 is an error.
} else {
// atoi returns 0 on error, so if 0 is a valid value you'll
// need special case handling to determine if you've got a
// "valid" 0 or not.
amount = atoi(line);
free(line);
}
https://stackoverflow.com/questions/61493690
复制