Home > Enterprise >  Getchar() skips the first value scanned in while loop
Getchar() skips the first value scanned in while loop

Time:10-05

I am trying to select all individual values scanned (cannot use arrays or strings) one at a time. For now, it skips the first value implemented by the user and I do not know why. I would like the loop to stop when getchar reaches "=" which will be at the end of the scanned value.

int main () {
char c;
while(scanf("%c", &c) != '=') {
 c=getchar();
 printf("print ");
 putchar(c);

 }
return 0;
}

In the terminal, when I input "a=" I only receive the "=" instead of "a". Can someone help?

CodePudding user response:

The condition in the while loop and the following call of getchar do not make a sense.

while(scanf("%c", &c) != '=') {
 c=getchar();
 //...

For example *The C Standard, 7.21.6.4 The scanf function)

3 The scanf function returns the value of the macro EOF if an input failure occurs before the first conversion (if any) has completed. Otherwise, the scanf function returns the number of input items assigned, which can be fewer than provided for, or even zero, in the event of an early matching failure.

And the read character by the call of scanf is not outputted.

You should write

char c;
while( scanf(" %c", &c) == 1 && c != '=') {
 printf("print %c", c);
}

Pay attention to that this call of scanf

scanf( " %c", &c)

will skip white space characters. If you want to output any character then you need to remove the blank before the conversion specifier like

scanf( "%c", &c)
       ^^^^ 

If you want to use getchar then the loop will look like

int c;
while( ( c = getchar() ) != EOF && c != '=') {
 printf("print %c", c);
}

In this case as you see the variable c must be declared as having the type int.

CodePudding user response:

The scanf() function returns the number of fields that were successfully converted and assigned.

You can read more here: https://www.ibm.com/docs/en/i/7.3?topic=functions-scanf-read-data

In your case, it will return 1 if c is scanned and assigned successfully, else 0.

The above documentation is platform-specific, but the below approach can still be applicable everywhere.

If you want your loop to end when the char is "=", then you can simply compare with if condition and break the loop:

int main () {
char c;
while(1) {
 c=getchar();
 if (c == '=') {
   break;
 }
 printf("print ");
 putchar(c);

 }
return 0;
}
  • Related