while循环导致程序

时间:2017-01-08 04:58:50

标签: c while-loop

void answerme();

int main() {

 char *answer = malloc (MAX_NAME_SZ);
 ....

printf ("\nWould you like to begin? [Y/N]");
fgets (answer, MAX_NAME_SZ, stdin);

answerme();

if(*answer == 'y' || *answer == 'Y'){
getinfo();
printf("\nprogram starting now...");
}


else if(*answer == 'n' || *answer == 'N'){
printf("\nThank you, program will close now....");
return 0;
}
...
}                 //end of main


void answerme(){                    
 char *answer = malloc (MAX_NAME_SZ);
 while(*answer !='n' && *answer != 'N' && *answer != 'y' && *answer != 'Y'){
    printf("\nPlease enter [Y], or [N]");
    fgets (answer, MAX_NAME_SZ, stdin);
 }

};

这个while循环或整个函数的重点在于它检查用户是否用y / n而不是另一个随机密钥回答了问题。我希望这个while循环继续向用户询问Y / N输入,直到用户输入它为止。但是由于某些原因,当这个程序运行时,第一步会询问您是否要开始该程序,如果您确实回答Y,它将由于某种原因告诉您"请输入Y或N"即使你确实输入了正确的答案,然后当你输入例如" n"甚至任何其他随机的信件,它仍然会让你通过。因此它似乎注册了输入,但由于某种原因,它仍然要求运行while循环而不是跳到if(answer == Y)或if(answer == N)。

有谁知道这是怎么回事?

一旦用户说'#34; Y"并开始该程序将有一条消息要求用户输入某些信息,这些信息存储到我创建的结构中(未在代码中显示),但是使用此while循环,这会以某种方式被跳过。如果我取消这个循环,整个程序工作正常,但当然用户将能够跳过程序的步骤而不严格输入我对他的要求。

如果有更好的替代方式将用户限制为只输入我所问的内容,请赐教我,因为这导致我过去3天的问题和头痛。谢谢!

2 个答案:

答案 0 :(得分:2)

问题是你在函数中设置变量*answer,主程序中还有另一个变量malloc()。但是,看起来它们应该是相同的变量。

要解决此问题,请仅声明一个并在两个函数之间共享。通过在任何函数之外声明它,或者将它从main传递给子函数来做到这一点。请注意,它只应为void answerme (char *answer) { while (*answer !='n' && *answer != 'N' && *answer != 'y' && *answer != 'Y') { printf ("\nPlease enter [Y], or [N]"); fgets (answer, MAX_NAME_SZ, stdin); } } int main() { char *answer = malloc (MAX_NAME_SZ); .... printf ("\nWould you like to begin? [Y/N]"); fgets (answer, MAX_NAME_SZ, stdin); answerme(answer); if (*answer == 'y' || *answer == 'Y') { getinfo(); printf("program starting now...\n"); } else if (*answer == 'n' || *answer == 'N') { printf("Thank you, program will close now.\n"); return 0; } ... } //end of main 一次。

参数传递技术的示例是:

'price_changes' => array(
    'color' => array(
        'Red' => '2',
        'Blue' => '-10%',
    ),
    'size' => array(
        'Large'  => '+1',
        'Medium'   => '-3',
    ),
),

答案 1 :(得分:0)

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define SIZE 10
void answerme();

int main() {

char answer[SIZE]="0";


printf ("\nWould you like to begin? [Y/N]");
scanf(" %s",answer);
if((strcmp(answer,"y")==0) || (strcmp(answer,"Y")==0))
{
    printf("Answer is y\n");
    printf("\nprogram starting now...");
    answerme();
}
else
{
    printf("Wrong input..exiting\n");
    exit(1);
}
return 0;
}

void answerme()
{                    
    char answer[SIZE]="0";
    do
    {
           printf("\nPlease enter [Y], or [N]");
           scanf(" %s",answer);
           printf("You entered %s\n",answer);
    }while((strncmp(answer,"y",1)!=0) && (strncmp(answer,"Y",1)!=0) && (strncmp(answer,"n",1)!=0) && (strncmp(answer,"N",1)!=0));

}