简体   繁体   中英

scanf not working correclty in this c program

I have wrote a small code to get value from Fahrenheit to Celsius. I wanted to keep inputting data until I press any other key than 'y'. But this loop doesn't work that way and stops after one iteration.

#include <stdio.h>

int main()
{
char ch='y';
int far, cen;
do {
    printf("again\n");
    scanf("%d",&far);
    //cen = (5.0/9.0)*(far-32);//integer division will truncate to zero so we can make 5/9 to 5.0 / 9.0
    cen = (5*(far-32))/9;//or this way we can use this formula
    printf("\n%d\t%d",far, cen);
    printf("ch=%c",ch);
    scanf("%c",&ch);
    }while(ch == 'y');

return 0;
}

What is the problem here? PS I added a line and made a new code like this

#include <stdio.h>

int main()
{
char ch='y';
int far, cen;
do {
    printf("again\n");
    scanf("%d",&far);//here we press carriage return. this value is in stdin
    //cen = (5.0/9.0)*(far-32);//integer division will truncate to zero so we can make 5/9 to 5.0 / 9.0
    cen = (5*(far-32))/9;//or this way we can use this formula
    printf("\n%d\t%d",far, cen);
    scanf("%c",&ch);//putting a space before %c makes the newline to be consumed and now it will work well
    if((ch == '\r')|| (ch == '\n'))
        printf("1\n");
    printf("ch=%c",ch);//this takes the carriage return in stdin buffer
    }while(ch == 'y');

return 0;
}

I need to know carriage return here is \\r or \\n?

When the value for scanf("%d",&far); is entered and press enter, the scanf stores the carriage return in the buffer. When it encounters the second scanf in the code scanf("%c",&ch); it takes the carriage return present in the buffer as the input to 'ch'. So it doesn't wait for the user input.

Please have a look at the post here

As indicated in one of the reply the solution is to put a space in scanf

scanf(" %c",&ch);

You should always check the return value of scanf . Your first use of scanf may fail if the user does not enter a valid integer, in which case, you are using far without initialising it (which is undefined behaviour). scanf returns the number of items that were successfully scanned. If you are requesting scanf to scan one integer, then it should return 1 if it successfully managed to scan an integer.

int scanresult = scanf("%d", &far);
if (scanresult != 1)
{
    puts("Invalid input or unexpected end of input");
    return 1;
}

In addition, the %c conversion specifier is unique in that it does not cause scanf to gobble up any preceding whitespace unlike the other conversion specifiers. To force scanf to gobble up the whitespace (such as linefeeds, carriage returns, spaces, tabs etc), simply put a space character before the %c , eg

scanresult = scanf(" %c", &ch);

For scanf , the space character is actually a directive to parse and skip all whitespace.

This is because of the previous newline character remaining in the buffer. You can simply replace scanf by this line:

while((ch = getchar()) == '\n');

You'll be needing the same technique in combination with ungetc() in many occasions.

Add fflush() function, just above scanf("%c", &ch). Because buffer of CONSOLE INPUT stores characters that not returned to program. Which is ENTER pressed in previous scanf:

#include <stdio.h>

int main() {
   char ch='y';
   int far, cen;
do {
   printf("again\n");
   scanf("%d",&far);
   //cen = (5.0/9.0)*(far-32);//integer division will truncate to zero     so we can make 5/9 to 5.0 / 9.0
   cen = (5*(far-32))/9;//or this way we can use this formula
   printf("\n%d\t%d",far, cen);
    printf("ch=%c",ch);

   scanf("%c",&ch);    // This scanf will be ignored, because loads last
                       // character from buffer that can be recognized 
                       // by scanf which is pressed "ENTER" from previous scanf 
   printf("%d", ch)     // Shows 10, which is ASCII code of newline
   fflush(stdin);       // Clear buffer
   scanf("%c",&ch);     // Now it will prompt you to type your character.

   // printf("%c"ch); //Without fflush, it must show 10, which is \n code    
   }while(ch == 'y');

    return 0;
   }

如果在Y之后按“空格”或“返回”,则这是您在%C中找到的字符

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM