gpt4 book ai didi

C 编程。尝试循环诱使用户输入正数

转载 作者:行者123 更新时间:2023-11-30 15:16:17 24 4
gpt4 key购买 nike

这里是初学者。我试图诱使用户输入正数。然而,当用户输入错误的数字时,while 循环似乎不起作用。

输出:

Please enter a positive integer: -3
I'm sorry, you must enter a positive integer greater than zero: why?
I'm sorry, you must enter a positive integer greater than zero: -42
I'm sorry, you must enter a positive integer greater than zero: 42
The positive integer was : 42
Press any key to continue....

代码:

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
void clear_keyboard_buffer(void);
int main()
{
int k;
printf("Please enter a positive integer: ");
scanf("%d", &k);
if (k > 0)
{
clear_keyboard_buffer();
printf("The positive integer was: %d ", k);

}
while (k<=0)
{
printf("I'm sorry, you must enter a positive integer greater than zero: ");
scanf("%d", &k);
return 0;
}
}

void clear_keyboard_buffer(void)
{
char ch;
scanf("%c", &ch);
while (ch != '\n')
{
scanf("%c", &ch);
}
}

最佳答案

好吧,我认为最简单的方法是向您展示一些可以实现您想要的功能的代码,以及一些关于为什么应该这样做的注释:

#include <stdio.h>

int main(void) /* note the void here, it says "no parameters"! */
{
int k;

/* here we don't use printf() because there is no formatting to do */
fputs("Please enter a positive integer: ", stdout);

scanf(" %d", &k); /* note the space, it consumes any whitespace */

while (k < 1)
{
fputs("I'm sorry, you must enter a positive integer greater "
"than zero: ", stdout);
scanf(" %d", &k);
}

printf("You entered `%d'\n", k);

return 0;
}

您仍然应该检查scanf()的返回值以获取生产质量代码,因为可能出现错误(例如,用户输入了某些内容)这不是一个数字...)

话虽如此,对于真正可靠的用户输入,我建议完全放弃 scanf() 并仅使用例如fgets() 读取一行输入(无论什么),然后解析自己。 strtol() 可以派上用场......

只是为了让您了解我在说什么,这里有一个非常简单但可靠的解决方案:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static int readInt(void)
{
char buf[1024];
int input;
char *endptr;

fgets(buf, 1024, stdin);

/* strip off "end of line" characters */
buf[strcspn(buf, "\r\n")] = 0;

input = strtol(buf, &endptr, 10);

/* sanity check, only accept inputs that can be wholly parsed as
* an integer
*/
if (buf[0] == 0 || *endptr != 0) input = -1;

return input;
}

int main(void)
{
int k;

fputs("Please enter a positive integer: ", stdout);

k = readInt();

while (k < 1)
{
fputs("I'm sorry, you must enter a positive integer greater "
"than zero: ", stdout);
k = readInt();
}

printf("You entered `%d'\n", k);

return 0;
}

关于C 编程。尝试循环诱使用户输入正数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33161091/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com