Home > other >  scanf("%f",&aa) VS scanf("%f",&aa) in a while loop
scanf("%f",&aa) VS scanf("%f",&aa) in a while loop

Time:11-02

I use the program below to calculate the absolute value of a number that I write. The program should stop when aa becomes n.

#include <stdio.h>
int main()
{
float a;
char ap;
printf("Start? Press n for no.\n");
scanf("%c",&ap);
while(ap!='n'){
  printf("Give a number\n");
  scanf("%f",&a);
    if(a<0){
    a=-a;
    }
  printf("Abs=%f\n",a);
  printf("Continue? Press n for no.\n");
  scanf("%c",&aa);
}
printf("Exit");
return 0;    
}

The program seems to ignore scanf("%c",&aa) in the while loop and that's my problem. Italics are input bold are output:

Start? Press n for no.

y

Give a number

4

Abs=4.000000

Continue? Pres n for no.

Give a number

5

Abs=5.000000

Continue? Pres n for no.

Give a number

n

Abs=5.000000

Continue? Pres n for no.

Exit

The problem is solved when I replace scanf("%c",&aa) with scanf(" %c",&aa) (see the space). Also, everything is ok when aa is a number. The program works fine and it stops when aa becomes 0.

#include <stdio.h>
int main()
{
float a, aa;
printf("Start? Press 0 for no.\n");
scanf("%f",&aa);
while(aa!=0){
  printf("Give a number\n");
  scanf("%f",&a);
    if(a<0){
    a=-a;
    }
  printf("Abs=%f\n",a);
  printf("Continue? Pres 0 for no.\n");
  scanf("%f",&aa);
}
printf("Exit");
return 0;
}

What is that?

Thanks in advance!

CodePudding user response:

Space before %c removes any white space (blanks, tabs, or newlines). It means %c without space will read white space like new line(\n), spaces(‘ ‘) or tabs(\t). By adding space before %c, we are skipping this and reading only the char given.

  • Related