嵌套If语句忽略scanf函数

时间:2018-04-22 11:34:32

标签: if-statement

我做了一个用户输入x坐标和y坐标的程序。如果用户输入一个字母,我希望重复输入,直到输入有效输入。经过3次尝试,程序将结束。但是每次我运行程序并输入一个测试字符时程序都会跳过scanf函数并且不测试嵌套的if循环,我试过在scanf函数中添加一个空格但是这似乎根本不起作用。非常感谢一些帮助,谢谢:)

代码:

printf("Insert first vector:\n");
vector1 = scanf(" %f %f",&x1,&y1);
printf("x1 %f y1 %f \n",x1,y1);
if(vector1 == 0)
{
  printf("Invalid input\n");
  printf("Insert first vector;  \n");
  vector2 = scanf(" %f %f",&x1,&y1);
   if(vector2 == 0)
   {
     printf("Invalid input\n");
     printf("Insert first vector;  \n");
     vector3 = scanf(" %f %f",&x1,&y1);
      if(vector3 == 0)
      {
       printf("Invalid input \n");
       x1=WRONG;

1 个答案:

答案 0 :(得分:0)

我假设您正在使用C语言。

int count = 1;
do {
    printf("Insert First Vector: ");
    fflush(stdin);
    vector1 = scanf("%f %f", &x1, &y1);
    count++;
} while (vector == 0 && count <= 3);

尝试使用上面的代码。

我只是为了简单起见而使用do while循环。

相关问题