开发者

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';
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜