简体   繁体   中英

C Scanf skipping in Xcode

new guy here. I've been at this for a month or so (C to Obj C to Cocoa to iOS Apps progression)

Upon returning to some basic C, I am stumped with the apparently common "scanf skips the next scanf since it's eating the return keystroke" issue. I've tried adding #c to the second scanf, i've tried adding a space in there too, but it still skips the second scanf and I'm always returning 0 as my average. I know there are better input commands than scanf. But for now, there has to be a way to get something as simple as this to work?

Thanks! ~Steve

int x;
int y;

printf("Enter first number:");
scanf("#i", &x);

printf("Enter second number:");
scanf("#i", &y);

printf("\nAverage of the two are %d", ((x+y)/2));

you should use %d format specifier to read integer input.

scanf("%d", &x); 
scanf("%d", &y);  

And Print average by casting to float

printf("\nAverage of the two are %6.2f", ((float)(x+y)/2));

Test code:

#include<stdio.h>
int main()
{

int x;
int y;

printf("Enter first number:");
scanf("%d", &x);

printf("Enter second number:");
scanf("%d", &y);

printf("\nAverage of the two are %6.3f\n", ((float)(x+y)/3));
return 0;
}

When you hit enter key after entering first number the new line character left on stdin. Therefore, it takes new line character as next input(second number). You should leave a white space before %d in second scanf() function. scanf(" %d", &y);

int x;
int y;

printf("Enter first number:");
scanf("%d", &x);

printf("Enter second number:");
scanf(" %d", &y);

printf("\nAverage of the two are %d", ((x+y)/2));

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