I'm not fully sure that this is what you're looking for, but if your question is how to read an integer using <stdio.h>, then the proper syntax is
int myInt;
scanf("%d", &myInt);
You'll need to do a lot of error-handling to ensure that this works correctly, of course, but this should be a good start. In particular, you'll need to handle the cases where
- The
stdinfile is closed or broken, so you get nothing at all. - The user enters something invalid.
To check for this, you can capture the return code from scanf like this:
int result = scanf("%d", &myInt);
If stdin encounters an error while reading, result will be EOF, and you can check for errors like this:
int myInt;
int result = scanf("%d", &myInt);
if (result == EOF) {
/* ... you're not going to get any input ... */
}
If, on the other hand, the user enters something invalid, like a garbage text string, then you need to read characters out of stdin until you consume all the offending input. You can do this as follows, using the fact that scanf returns 0 if nothing was read:
int myInt;
int result = scanf("%d", &myInt);
if (result == EOF) {
/* ... you're not going to get any input ... */
}
if (result == 0) {
while (fgetc(stdin) != '\n') // Read until a newline is found
;
}
Hope this helps!
EDIT: In response to the more detailed question, here's a more appropriate answer. :-)
The problem with this code is that when you write
printf("got the number: %d", scanf("%d", &x));
This is printing the return code from scanf, which is EOF on a stream error, 0 if nothing was read, and 1 otherwise. This means that, in particular, if you enter an integer, this will always print 1 because you're printing the status code from scanf, not the number you read.
To fix this, change this to
int x;
scanf("%d", &x);
/* ... error checking as above ... */
printf("got the number: %d", x);
Hope this helps!
Answer from templatetypedef on Stack OverflowI'm not fully sure that this is what you're looking for, but if your question is how to read an integer using <stdio.h>, then the proper syntax is
int myInt;
scanf("%d", &myInt);
You'll need to do a lot of error-handling to ensure that this works correctly, of course, but this should be a good start. In particular, you'll need to handle the cases where
- The
stdinfile is closed or broken, so you get nothing at all. - The user enters something invalid.
To check for this, you can capture the return code from scanf like this:
int result = scanf("%d", &myInt);
If stdin encounters an error while reading, result will be EOF, and you can check for errors like this:
int myInt;
int result = scanf("%d", &myInt);
if (result == EOF) {
/* ... you're not going to get any input ... */
}
If, on the other hand, the user enters something invalid, like a garbage text string, then you need to read characters out of stdin until you consume all the offending input. You can do this as follows, using the fact that scanf returns 0 if nothing was read:
int myInt;
int result = scanf("%d", &myInt);
if (result == EOF) {
/* ... you're not going to get any input ... */
}
if (result == 0) {
while (fgetc(stdin) != '\n') // Read until a newline is found
;
}
Hope this helps!
EDIT: In response to the more detailed question, here's a more appropriate answer. :-)
The problem with this code is that when you write
printf("got the number: %d", scanf("%d", &x));
This is printing the return code from scanf, which is EOF on a stream error, 0 if nothing was read, and 1 otherwise. This means that, in particular, if you enter an integer, this will always print 1 because you're printing the status code from scanf, not the number you read.
To fix this, change this to
int x;
scanf("%d", &x);
/* ... error checking as above ... */
printf("got the number: %d", x);
Hope this helps!
The typical way is with scanf:
int input_value;
scanf("%d", &input_value);
In most cases, however, you want to check whether your attempt at reading input succeeded. scanf returns the number of items it successfully converted, so you typically want to compare the return value against the number of items you expected to read. In this case you're expecting to read one item, so:
if (scanf("%d", &input_value) == 1)
// it succeeded
else
// it failed
Of course, the same is true of all the scanf family (sscanf, fscanf and so on).
What is a good way to take an integer as input while checking for input errors as letters?
When I used scanf() when mistakenly inputting a letter it ended up crashing the whole program.
c - What is the easiest way to get an int in a console app? - Stack Overflow
How to get input integer from user c - Stack Overflow
Integer input by user C programming - Stack Overflow
debugging - How to take integer input with scanf in C without using arrays? - Stack Overflow
Videos
#include <stdio.h>
int n;
scanf ("%d",&n);
See http://www.cplusplus.com/reference/clibrary/cstdio/scanf/
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);
}
scanf returns an integer indicating how many "things" it successfully read. You can test this in a conditional to see if it got what you were looking for. Example:
const int result = scanf ("%d",&righe);
if (1 != result) {
/* didn't get the 1 input we were looking for, do something about it! */
}
You'll want to distinguish between EOF and simply not an integer though.
Check the return value of scanf() it should return the number of converted strings, if it is != 1 the input couldn't be converted to an integer.
Reference :scanf
"...it work fine but i can't understand it.Can you please explain me?"
The scanf() function is the core of this piece of code.
scanf() returns the number of items successfully converted. In this example the program is attempting to convert 2 items, so checking that return is == 2 will confirm call was successful. Explicitly, the coder's intent appears to be to verify that the numeric value and the newline are captured. For this simple example, this code is sufficient, but scanf() is capable of more. At the same time, there are arguably better alternatives for user input.
Let me try: I didn't touch C++/C since 5 years so forgive my syntax errors.
Do-while:
#include <stdio.h>
int main()
{
int num;
char term;
do{
user_input = scanf("%d%c", &num, &term)
//Code for wrong input
}
while(user_input != 2 || term != '\n')
//Code for right input
return 0;
}
While:
#include <stdio.h>
int main()
{
int num;
char term;
user_input = scanf("%d%c", &num, &term)
while(user_input != 2 || term != '\n')
{
//Code for wrong input
user_input = scanf("%d%c", &num, &term) //In while loop you've to take input again
}
//Code for right input
return 0;
}
Like all of the other answers, the following solution violates the rule of not using arrays, because I cannot think of any clean solution to the problem which does not use them.
The problem with using scanf is that it will treat spaces and newline characters equally. This is not what you want.
For line-based user input, it makes more sense to always read one line at a time, and treat every line individually. In order to read one line of user input as a string, you can use the function fgets. You can then convert this string to numbers using the function sscanf or strtol.
Here is a solution that uses the function sscanf:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main( void )
{
for (;;) //infinite loop
{
char line[200];
int numbers[5];
int num_numbers;
//prompt user for input
printf( "Please enter up to 5 numbers: " );
//attempt to read one line of input from user
if ( fgets( line, sizeof line, stdin ) == NULL )
break;
//verify that line was not too long for input buffer
if ( strchr( line, '\n' ) == NULL && !feof( stdin ) )
{
printf( "Line too long for input buffer!\n" );
exit( EXIT_FAILURE );
}
//attempt to convert string to numbers
num_numbers = sscanf(
line,
"%d %d %d %d %d",
&numbers[0], &numbers[1], &numbers[2],
&numbers[3], &numbers[4]
);
//print result
if ( num_numbers == 0 || num_numbers == EOF )
{
printf( "Was not able to match any numbers.\n" );
}
else
{
printf( "Successfully matched %d numbers:\n", num_numbers );
for ( int i = 0; i < num_numbers; i++ )
{
printf( "%d\n", numbers[i] );
}
}
printf( "\n" );
}
}
This program has the following behavior:
Please enter up to 5 numbers: 20 30 35 40
Successfully matched 4 numbers:
20
30
35
40
Please enter up to 5 numbers:
Was not able to match any numbers.
Please enter up to 5 numbers: 12 17
Successfully matched 2 numbers:
12
17
Please enter up to 5 numbers: 5
Successfully matched 1 numbers:
5
Here is a solution which uses the function strtol instead of sscanf:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NUMBERS 5
int main( void )
{
for (;;) //infinite loop
{
char line[200], *p = line, *q;
long numbers[MAX_NUMBERS];
int num_numbers = 0;
//prompt user for input
printf( "Please enter up to 5 numbers: " );
//attempt to read one line of input from user
if ( fgets( line, sizeof line, stdin ) == NULL )
break;
//verify that line was not too long for input buffer
if ( strchr( line, '\n' ) == NULL && !feof( stdin ) )
{
printf( "Line too long for input buffer!\n" );
exit( EXIT_FAILURE );
}
//convert as many numbers as possible
for ( int i = 0; i < MAX_NUMBERS; i++ )
{
numbers[i] = strtol( p, &q, 10 );
if ( p == q )
break;
p = q;
num_numbers++;
}
//print result
if ( num_numbers == 0 )
{
printf( "Was not able to match any numbers.\n" );
}
else
{
printf( "Successfully matched %d numbers:\n", num_numbers );
for ( int i = 0; i < num_numbers; i++ )
{
printf( "%ld\n", numbers[i] );
}
}
printf( "\n" );
}
}
This second program has exactly the same output as the first program.
I would suggest to get a whole line and then parse it:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
char line[1024];
if (fgets(line, 1024, stdin) == NULL) {
perror("Error occured");
return 2;
}
if (line[strlen(line)-1] != '\n') {
while (getchar() != '\n');
} else {
line[strlen(line)-1] = '\0';
}
int counter = 0;
for (char * word = strtok(line, " "); word; word = strtok(NULL, " ")) {
int number = atoi(word);
// do something with your number
counter++;
}
if (counter == 0) {
return 1;
}
return 0;
}