Help with basic reading user input in C
I am currently just learning C and for a project I need to read in integer inputs from the user. Currently I am using code that looks like this:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int a, b;
printf("Please ente开发者_运维百科r your first number");
while((a = getchar()) != '\n') {
}
printf("test");
return 0;
}
Im not sure how to get the number with getchar and then store it in a variable i can use. Also I'm using = '\n' in the while statement because I don't really understand how EOF works (as in the K&R book) because whenever i use EOF i go into this loop i cant get out of.
Thanks for any advice anyone can offer.
You can use scanf.
Have a look at this example:
printf("Please enter your first number ");
int number=0;
scanf ("%d",&number);
The scanf answer above mine is correct, but if you haven't read about addresses or format strings, it may be difficult to grok.
You can convert your character to its integer equivalent by subtracting '0' from it:
char c = getchar();
int n = c - '0';
精彩评论