Why does the following code execute - when a decimal number is entered - at first, but on the second iteration scanf directly returns 0, and the loop breaks?
#include <stdio.h>
int main(){
int num = 1;
while(num != 0){
printf("input integer: ");
if(scanf("%d", &num) == 0)
break;
printf("out: %d\n", num);
}
return 0;
}
If I enter, for example, 5.55, it prints 5 (scanf returns 1 and printf executes), however on the next iteration it [scanf] returns 0 and the loop breaks. Why does scanf return 1 in the first place?
Depending on the format specifier in your format string, scanf consumes as much input from input stream as matches for the specified argument type.
For %s it reads until it sees a space or end of line.
For %d it reads as long as it sees digits.
If you use %d and then enter "5.55" in stdin, scanf will only consume the first '5' and the remaining ".55" will stay in the buffer.
On your first call, scanf is able to convert input for the first parameter. As a result, it will return 1 and the value 5 is assigned to num.
The data in input buffer does not go away between calls to scanf.
In your second call you also use %d but now, scanf sees a '.' that does not match the required format. As a result, no input is consumed, no value is converted and the return value is 0.
This will stay the same for any following call until you consume input in another way.
i want to check if all inputs are of type double in this code in c by using the returned value of scanf:
#include <stdio.h>
int main()
{
double a,b,c;
int x = scanf("%lf %lf %lf", &a, &b, &c);
printf("%d", x);
}
but this is what i'm getting:
here i expect 1 but i'm getting 0:
here i expect 2 but i'm getting 1:
According to scanf man
The format string consists of a sequence of directives which describe
how to process the sequence of input characters. If processing of a
directive fails, no further input is read, and scanf() returns
Thus
For Case 1.
scanf will stops reading when it detects the mismatch for the first specifier.
For Case 2.
scanf will stops reading when it detects the mismatch for the second specifier.
scanf stops processing input as soon as any conversion fails, going from left to right, it doesn't try to process the remaining inputs.
So when you enter
b b 2.8
it fails when trying to do the first %lf conversion. Since no conversions have been done, it returns 0.
When you enter
2 x 2.1
it successfully converts 2 to a double, but fails on x, so it doesn't process 2.1 and returns 1.
#include<stdio.h>
int main(){
int n;
printf("%d\n",scanf("%d",&n));
return 0;
}
I wonder why the output of this program is always '1' ?!
What's actually happening here ?
I suspect you wanted to use
int n;
scanf("%d", &n);
printf("%d\n", n);
but what you wrote is equivalent to
int n;
int num = scanf("%d", &n); // num is the number of successful reads.
printf("%d\n", num);
The program is just about exactly equivalent to
#include <stdio.h>
int main() {
int n;
int r = scanf("%d", &n);
printf("%d\n", r);
return 0;
}
So if you run this program, and if you type (say) 45, then scanf will read the 45, and assign it to n, and return 1 to tell you it has done so. The program prints the value 1 returned by scanf (which is not the number read by scanf!).
Try running the program and typing "A", instead. In that case scanf should return, and your program should print, 0.
Finally, if you can, try running the program and giving it no input at all. If you're on Unix, Mac, or Linux, try typing control-D immediately after running your program (that is, without typing anything else), or run it with the input redirected:
myprog < /dev/null
On Windows, you might be able to type control-Z (perhaps followed by the Return key) to generate an end-of-file conditions. In any of these cases, scanf should return, and your program should print, -1.
#jishnu, good question and the output which you're getting is also correct as you are only reading one value from standard input (stdin).
scanf() reads the values supplied from standard input and return number of values successfully read from standard input (keyboard).
In C, printf() returns the number of characters successfully written on the output and scanf() returns number of items successfully read. Visit https://www.geeksforgeeks.org/g-fact-10/ and read more about it.
Have a look at the following 2 code samples.
Try the below code online at http://rextester.com/HNJE76121.
//clang 3.8.0
#include<stdio.h>
int main(){
int n, n2;
printf("%d\n",scanf("%d%d",&n, &n2)); //2
return 0;
}
In your code, scanf() is reading only 1 value from the keyboad (stdin), that is why output is 1.
//clang 3.8.0
#include<stdio.h>
int main(){
int n;
printf("%d\n",scanf("%d",&n)); //1
return 0;
}
In your program scanf returns 1 when successfully some value is taken by scanf into n and that is why you are always getting 1 from your printf("%d\n",scanf("%d",&n));.
You should modify your code like following
#include<stdio.h>
int main(){
int n;
scanf("%d",&n);
printf("%d\n",n);
return 0;
}
In man scanf,
Return Value
These functions return the number of input items successfully matched and assigned, which can be fewer than provided for, or even zero in the event of an early matching failure.
In your program, it just match 1 input, so the function scanf will return 1, if you input an legal value that can match a %d, else it will return 0.
In your situation, you might always satisfy this requirements, so it always return 1.
scanf returns the number of successful conversion and assignments. In your case, you're only scanning for one argument, so scanf will either return a 1 on success, a 0 on a matching failure (where the first non-whitespace input character is not a decimal digit), or EOF on end-of-file or error.
When you call printf, each of its arguments is evaluated and the result is passed to the function. In this case, evaluation involves calling the scanf function. The value returned by scanf is then passed to printf.
It's essentially the same as writing
int count = scanf( "%d", &n );
printf( "%d\n", count );
For giggles, see what happens when you enter abc or type CtrlD (or CtrlZ on Windows).
Note that printf also returns a value (the number of bytes written to the stream), so you can write something ridiculous1 like
printf( "num bytes printed = %d\n", printf( "num items read = %d\n", scanf( "%d", &n ) ) );
Joke. Don't do that.
scanf returns number of successful conversions.
Try changing your scanf to as shown below....
you will notice printing 2 after inputting two valid integers.
int n1 =0;
int n2 =0;
int i = scanf("%d %d",&n1,&n2);
In C programming, scanf() takes the inputs from stdin() which is the keyboard and returns the number of successful inputs read
and printf() returns the number of characters written to stdout() which is the display monitor.
In your program scanf() is reading only one input which is getting returned and is printed by printf(). So, whatever may be the input the output is always 1 as it is reading only one input.
Here take a look at this C program:
#include<stdio.h>
int main(){
int n, n2;
printf("%d\n",scanf("%d %d",&n,&n2));
return 0;
}
It takes input or reads two integers from stdin() using scanf(), so the output will always be 2.
**Note: The output is 0 if your input is not integer, as it reads integer only.
The documentation of scanf() says the return value is:
Number of receiving arguments successfully assigned (which may be zero in case a matching failure occurred before the first receiving argument was assigned), or EOF if input failure occurs before the first receiving argument was assigned.
The code you would instead want is:
#include<stdio.h>
int main(){
int n;
scanf("%d",&n);
printf("%d\n",scanf("%d",&n));
return 0;
}
If you use this code as an example,
It shows : warning: implicit declaration of function 'printf' [-Wimplicit-function declaration]
int main()
{
char b[40];
printf(" %d", scanf("%s", b));
getchar();
}
Return value : -1
Outputs of the functions like printf and scanf can be use as a parameter to another function.
scanf() is a function which is integer return type function. It returns total number of conversion characters in it. For ex if a statement is written as :
int c;
c=scanf("%d %d %d");
printf("%d",c);
Then output of this program will be 3.
This is because scanf() is integer return type function and it returns total no of conversion characters, thus being 3 conversion characters it will return 3 to c.
So in your code scanf() returns 1 to printf() and thus output of program is 1.
This is because if more than one statement are used in printf() execution orders starts from right to left.
Thus scanf() is executed first followed by printf().
The input and output for the following program are given below:
#include<stdio.h>
int main(){
int a=0, b=100, c=200;
scanf("%d,%d,%d",&a,&b,&c);
printf("%d %d %d\n",a,b,c);
return 0;
}
Input-1:
1,2,3
Output-1:
1 2 3
So the first output is correct and as expected.
Input-2:
1 2 3
Output-2:
1 100 200
Here it reads first integer correctly but I am not able to understand, how the scanf() reads the data after first integer when we are not giving the input in specified format?
As values entered after first integer are not assigned to any variables, What happens to those values?
Are they written on some random memory locations?
Here it reads first integer correctly but I am not able to understand,
how the scanf() reads the data after first integer when we are not
giving the input in specified format?
scanf stops at the first mismatch and leaves the rest of the target objects untouched. You can inspect the return value to determine how many "items" scanf matched.
As values entered after first integer are not assigned to any
variables, What happens to those values?
The unmatched data is left in the input buffer, available for a subsequent read using scanf, fgets etc.
I used getchar() and putchar() after last printf() statement in the
program but nothing was read.
Strange. You should be able to get away with something like:
int ch;
while ((ch = getc(stdin)) != EOF)
putchar(ch);
TL;DR answer: It doesn't. It stops reading.
To clarify, input is not in specified format is a matching failure for scanf(). That is why it's always recommended to check the return value of scanf() to ensure all the input items got scanned successfully.
In the second input scenario, the scanf() has failed to scan all the input parameters because of the format mismatch of expected and received inputs [and you have no idea of that]. Only the value of a has been scanned successfully, and reflected.
[Just for sake of completeness of the answer]:
After the input value of a, due to the absence of a , in the input, mismatch happened and scanf() stopped scanning, returning a value of 1. That's why, b and c prints out their initial values.
#include <cstdio>
using namespace std;
int main()
{
int i,a;
printf("%d",printf("PRINT %d\t",scanf("%d %d",&i,&a)));
return 0;
}
This code is giving output
PRINT 2 8
I want to know how it is giving the same output for any number inputted. I'm a new user and sorry if I'm wrong somewhere. Thank You.
This code is the same as
int main()
{
int i,a;
int p, s;
s = scanf("%d %d",&i,&a);
p = printf("PRINT %d\t",s)
printf("%d", p);
return 0;
}
scanf returns the number of items assigned. In your case 2 variables, if successful.
Then you print the string "PRINT 2\t".
printf returns the number of characters written, 8 in this case.
And then you print that number, 8. Which means all the output of your program is "PRINT 2\t8"
scanf returns the number of items successfully read (in this case 2).
On success, the function returns the number of items of the argument
list successfully filled.
printf returns the number of characters successfully printed (in this case, the inner printf returns 8).
On success, the total number of characters written is returned.
If a writing error occurs, the error indicator (ferror) is set and a
negative number is returned.
Hence, elaborating the statement printf("%d",printf("PRINT %d\t",scanf("%d %d",&i,&a))):
Your innermost scanf would return 2, since it reads 2 integers.
Then your inner printf would become printf("PRINT %d\t", 2) and would write 8 characters PRINT 2\t, hence returning 8.
Then your outer printf would become printf("%d", 8) and write 8, making your combined output PRINT 2 8.