Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the easiest way to get an int in a console app?

I want to process user input as an integer, but it seems as though C has no way to get an int from stdin. Is there a function to do this? How would I go about getting an int from the user?

like image 952
Jon Chasteen Avatar asked May 14 '09 19:05

Jon Chasteen


People also ask

How to get integer input in c sharp?

To read inputs as integers in C#, use the Convert. ToInt32() method. The Convert. ToInt32 converts the specified string representation of a number to an equivalent 32-bit signed integer.

How to read number in C# from Console?

ReadLine() method in C# reads a string value from the console. If we want to read an integer value from the console, we first have to input the integer value in a string and then convert it to an integer. The int. Parse() method is then used to convert a string to an integer value in C#.


2 Answers

#include <stdio.h>

int n;
scanf ("%d",&n);

See http://www.cplusplus.com/reference/clibrary/cstdio/scanf/

like image 61
Marc W Avatar answered Oct 29 '22 15:10

Marc W


scanf() is the answer, but you should certainly check the return value since many, many things can go wrong parsing numbers from external input...

int num, nitems;

nitems = scanf("%d", &num);
if (nitems == EOF) {
    /* Handle EOF/Failure */
} else if (nitems == 0) {
    /* Handle no match */
} else {
    printf("Got %d\n", num);
}
like image 36
dwc Avatar answered Oct 29 '22 17:10

dwc