tags:

views:

66

answers:

4

I am wondering if there is a function I could use in the standard libary. Do I need another library (BTW, I am developing for unix).

+3  A: 

See the scanf() function in stdio.h. It takes a format specifier like printf() and pointers to the variables to store the user input in

Michael Mrozek
+5  A: 

Use scanf()

Format: int scanf ( const char * format, ... );

Read formatted data from stdin. Reads data from stdin and stores them according to the parameter format into the locations pointed by the additional arguments. The additional arguments should point to already allocated objects of the type specified by their corresponding format tag within the format string.

Example:

#include <stdio.h>
int main(void)
{
    int n;
    printf("Enter the value to be stored in n: ");
    scanf("%d",&n);
    printf("n= %d",n);
}

However have a look at this.

Prasoon Saurav
A: 

You seems quite new to C so let me add a little something to Prasoon answer, which is quite correct and complete, but maybe hard to understand for a beginner.

When using scanf( const char * format, ... ); in his exemple, Prasoon use :

scanf("%d",&n);

When using this, the "%d" indicate you're going to read an integer (See wikipedia for complete format list ).

The second argument (note that the ... indicates you can send any number of arguments) indicate the address of the variable in which you are gonna stock user entry.

+1  A: 

'Tis interesting - two answers so far both suggest scanf(); I wouldn't.

When everything goes right, scanf() is OK. When things go wrong, recovery tends to be hard.

I would normally use fgets() to read the user information for one line into a buffer (character array) first. I would then use sscanf() to collect information from the buffer into the target variables. The big advantage is that if the user types '12Z' when you wanted them to type two numbers, you can tell them what you saw and why it is not what you wanted much better. With scanf(), you can't do that.

Jonathan Leffler
@Jonathan: Perhaps you missed the link which I have given in my post.
Prasoon Saurav
@Prasoon: yes - I did miss it, since you didn't explain in the post why your suggestion to use scanf() is not necessarily a good idea.
Jonathan Leffler