如何为继续或停止创建单独的函数,因此可以随时引用那里。下面不是一个正确的 C,只是一个要实现的想法
main()
do{
request for input...
if found invalid, Continue or stop?
...
After one complete run
ask again for Continue or stop?
...
}while(Continue)
我已经尝试过这个,但是来自 feed,Continue 的值无法传递到主函数。我的逻辑有问题吗?或者有更简单的方法可以做到这一点。
struct Ans {
int Continue;
int Stop;
char choice;
};
struct Ans feed ;
void YesNo(){
int p=1;
int q=2;
char choice;
feed.Continue=0;
feed.Stop=0;
while (feed.Continue==0)
{
printf("\nDo you wish to try again (Type Y to continue Q to quit:");
scanf(" %c", &choice);
choice = toupper(choice);
if(choice == 'Y')
{
feed. Continue = p;
return;
}
else if(choice=='Q') {
feed.Stop = q;
return;
}
else
{
printf("\nError: Invalid choice\n");
do
{
feed.choice = getchar();
} while (feed.choice != '\n' && feed.choice != EOF);
}
}
}
void main{
Loop:do{
printf("Please enter(k):\n");
scanf("%d",&k);
struct Ans feed;
char str[N];
if (fgets(str, sizeof str, stdin))
{
flag = 0;
long value;
char *check;
value = strtol(str, &check, 0);
if (!isspace(*check) && *check != 0) flag = 1;
{
printf("\nInvalid Input\n");
}
while ( flag == 1)
{
YesNo();
flag = 0;
{
if (feed.Continue) {
goto Loop;
}
else if (feed.Stop) exit(0);
}
}
}
if ((k<0)||(k>N-1)) {
printf("Input value out of range");
}
YesNo();
{
if (feed.Continue) {
goto Loop;
}
else if (feed.Stop) exit(0);
}
//run something
do{
printf("\nDo you wish to try again (Type Y to continue Q to quit:");
scanf(" %c", &choice);
choice = toupper(choice);
}while((choice != 'Y') && (choice != 'Q'));
}while(choice == 'Y');
return ;
}
}
最佳答案
您可以将ContinueOrStop函数放在main函数之外,然后在需要时在main函数中调用
void ContinueORStop()
{
do{
request for input...
if found invalid, Continue or stop?
...
After one complete run
ask again for Continue or stop?
...
}while(Continue)
}
main()
{
ContinueOrStop();
}
关于c - 对 C 代码中的多个位置使用相同的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40310692/