gpt4 book ai didi

c - 输入数字错误时C中的跳转代码

转载 作者:行者123 更新时间:2023-11-30 16:42:18 25 4
gpt4 key购买 nike

我有一个代码。想法是当我需要输入数字但我输入非数字字符时,检查错误并要求我输入工作数字,或者继续或中断。但它会跳过不输入数字的代码。这是代码:

int EnterNumber(){
int number;
printf("Enter your's number:");
if(!scanf("%d", &number)){
puts("Keypress don't number!");
int choose = 0;
puts("Work:\n\t1. Continue 2. Break \nYour's number will choose:");
while(!scanf("%d", &choose)){ // here it jumped.I cann't enter number!
switch(choose){
case 1:
EnterNumber();
break;
case 2:
break;
default:
puts("Keyboard don't recognize");
break;
}
}
}

return number;
}

谁能帮我解决这个错误吗?

最佳答案

您似乎在帖子中实现了递归。但是代码中的某些行是不需要的,并且阻碍了递归算法的潜在效率。

递归算法的本质可以用两条语句来概括:

1) Each recursive call should be on a smaller instance of the same problem, that is, a smaller subproblem.
2) The recursive calls must eventually reach a base case, which is solved without further recursion.
(from here)

以下是对原始 EnterNumber() 函数的改编,简化为仅包含上面列出的递归算法的基本要素。

  • reads and tests input character (smaller instance...)
  • leaves when test fails criteria (base case...)

它可以根据需要进行扩展,以包含您在原始帖子中所需的其他功能(例如更多用户输入,或通知用户输入不是数字)

void EnterNumber(char a);

int main(void)
{

char c;
int num;

printf("Enter your number:");
scanf(" %c", &c);
// ^ notice space preceeding format char,
// comsumes newline from previous read and allows next input
num = isdigit(c);
EnterNumber(c);
printf("\nHit any key to exit\n");
getchar();
return 0;
}

/// Simple demo of recursion:
/// caches input as long as it is a number
/// outputs cache and exits if alpha char
void EnterNumber(char a)
{
if(isdigit(a) != 0)
{
printf("Enter your number:");
scanf(" %c", &a);
// ^ notice space preceeding format char,
// comsumes newline from previous read and allows next input
EnterNumber(a);
}
printf("%c\n", a);
}

关于 scanf() 格式字符串中的空格功能:

Whitespace character: the function will read and ignore any whitespace characters encountered before the next non-whitespace character (whitespace characters include spaces, newline and tab characters -- see isspace). A single whitespace in the format string validates any quantity of whitespace characters extracted from the stream (including none). (from here)

关于c - 输入数字错误时C中的跳转代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45882991/

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