对C代码中的多个位置使用相同的函数
如何为Continue或Stop创建一个单独的函数,以便随时参考。下面不是一个合适的C,只是一个实现什么的想法对C代码中的多个位置使用相同的函数,c,function,C,Function,如何为Continue或Stop创建一个单独的函数,以便随时参考。下面不是一个合适的C,只是一个实现什么的想法 main() do{ request for input... if found invalid, Continue or stop? ... After one complete run ask again for Continue or stop? ...
main()
do{
request for input...
if found invalid, Continue or stop?
...
After one complete run
ask again for Continue or stop?
...
}while(Continue)
我已经尝试过了,但是提要Continue中的值无法传递给main函数。我的逻辑有什么问题吗?或者有更简单的方法
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 ;
}
}
struct-Ans{
int继续;
int Stop;
字符选择;
};
结构和馈送;
void YesNo(){
int p=1;
int q=2;
字符选择;
feed.Continue=0;
feed.Stop=0;
while(feed.Continue==0)
{
printf(“\n是否要重试(键入Y继续Q退出:”);
scanf(“%c”,选择(&c));
选择=toupper(选择);
如果(选项='Y')
{
feed.Continue=p;
返回;
}
else if(选项=='Q'){
feed.Stop=q;
返回;
}
其他的
{
printf(“\n错误:无效选择\n”);
做
{
feed.choice=getchar();
}while(feed.choice!='\n'&&feed.choice!=EOF);
}
}
}
空主{
循环:做{
printf(“请输入(k):\n”);
scanf(“%d”和“&k”);
结构和馈送;
char-str[N];
如果(fgets(str,sizeof str,stdin))
{
flag=0;
长期价值;
字符*检查;
值=strtol(str和check,0);
如果(!isspace(*check)&&*check!=0)标志=1;
{
printf(“\n无效输入\n”);
}
while(标志==1)
{
YesNo();
flag=0;
{
if(feed.Continue){
后藤环;
}
否则如果(进给停止)退出(0);
}
}
}
如果((kN-1)){
printf(“输入值超出范围”);
}
YesNo();
{
if(feed.Continue){
后藤环;
}
否则如果(进给停止)退出(0);
}
//做点什么
做{
printf(“\n是否要重试(键入Y继续Q退出:”);
scanf(“%c”,选择(&c));
选择=toupper(选择);
}而((选择!='Y')&&(选择!='Q');
}while(choice='Y');
返回;
}
}
您可以在main函数之外创建ContinueOrStop函数,然后在需要时调用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到底是如何有效的?