Okay so I'm trying to do a basic program in VS. Enter a number then it gets printed out. 1 is always printed.
int main(){
printf("Enter an integer: ");
int n = scanf_s("%d", &n);
printf("%d", n);
}
You are assigning the returned value from scanf_s() to the variable n, that means that the program will print 1 in case a successful read happened.
What you should do is
int numberOfItemsMatched;
int readValue;
numberOfItemsMatched = scanf_s("%d", &readValue);
if (numberOfItemsMatched == 1)
printf("%d\n", readValue);
I hope the variable names are self explanatory, and it's always a good idea to use this kind of names.
return type of scanf is number of items read. so if scanf is succesful in reading an item, it returns one which is assigned to n here. hence the output is 1. So separate declaration of n and scanf.
Related
#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().
I am pretty sure this was asked before but I could not find any answers, so here I go. This is a simple line of code and I cannot get it to exit the while loop. If I change the || to && the loop just exit no matter what I press. Thank you for the answers.
#include <stdio.h>
int main()
{
int answer;
printf("Are you sure you want to exit the program? Type in 1 for yes and 2 for no.\n");
scanf("%d", answer);
//This is to check that the user inputs the right number if not error message is displayed
while(answer <1 || answer > 2)
{
printf("Please type in 1 to exit the program and yes and 0 to keep playing. \n");
scanf("%d", answer);
flushall();
}
return 0;
}
If You want to exit on 1, then You just need to check if input is equal to it, that is why I want to scan for more answers when it is not equal to 1. If it is then it will omit while loop and go directly to return 0.
Also I changed the way of usage of scanf - when you declare a variable (in Your case answer), system gives it an address in the memory. Then you use scanf to take an input from the user, and after you take the input, you write it on the address of that variable so that when you refer to it later, the system goes to the address and retrieve the value.
int main()
{
int answer;
printf("Are you sure you want to exit the program? Type in 1 for yes and 2 for no.\n");
scanf("%d", &answer);
//This is to check that the user inputs the right number if not error message is displayed
while(answer != 1)
{
printf("Please type in 1 to exit the program and yes and 0 to keep playing. \n");
scanf("%d", &answer);
}
return 0;
}
This is one the frequent cases of misunderstanding/forgetting how scanf works.
int scanf ( const char * format, ... );
reads formatted data from stdin.
It reads data from stdin and stores data 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 specifier within the format string.
It means that arguments should be pointers.
In your case:
int answer;
scanf("%d", answer);
answer is not a pointer but the variable (object) of type int.
To satisfy the scanf you have to use a pointer to the answer.
You can do it using the unary or monadic operator & which gives the address of a variable.
scanf("%d", &answer);
or you could use a pointer pointing to the answer:
int answer;
int answer_ptr = & answer;
scanf("%d", answer_ptr);
which is also correct but typically there is no need to go for this construction.
Secondly the line:
while(answer <1 || answer > 2)
You may want to modify it to
while (answer != 1 && answer != 2)
if you are interested in breaking the while loop when answer is being equal to 1 or 2.
I am learning C from a book and I am starting with loop instructions. But there is a sample code which I could not understand.
Can anyone tell me why author has used status = scanf("%ld", &num); ? Why there is a = with scanf ?
/* summing.c -- sums integers entered interactively */
#include <stdio.h>
int main(void)
{
long num;
long sum = 0L; /* initialize sum to zero */
int status;
printf("Please enter an integer to be summed ");
printf("(q to quit): ");
status = scanf("%ld", &num);
while (status == 1) /* == means "is equal to" */
{
sum = sum + num;
printf("Please enter next integer (q to quit): ");
status = scanf("%ld", &num);
}
printf("Those integers sum to %ld.\n", sum);
return 0;
}
Because scanf() returns a value indicating how well the string matched the format passed, i.e. how many parameters were successfuly filled with data.
You would know that if your read some kind of manual page, or the standard, if you ever encounter a function that you don't know, always read about it as much as you can, so you can understand how to use it.
scanf returns the number of successfully matched items from its specifier list. So, if you enter "q", scanf will return 0 (since "q" is not an integer), and the loop will terminate.
Please have a look at the man page of scanf(). It returns the number of items successfully scanned. So the return value is used to check the successfulness of scanf().
In your code,
status = scanf("%ld", &num);
// code
while (status == 1)
the return value of scanf() is stored into status and checked later to check whether scanf() has successfully scanned 1 item or not.
If it has returned 1, meaning a long int has been entered. Then the while() loop will continue, asking for the next input.
One you enter q, it won't match the coversion specifier %ld, hence scanf() will fail, hence it will return 0. Then the while() loop will terminate.
here is my code where i am facing a problem regarding datatypes in c
#include<stdio.h>
int main()
{
int a,b;
scanf("%d",&b);
printf("%d",b);
}
When In Entered Any Character Instead Of Integer values It always Prints 32. Am Not Getting Why Its printing 32.
The value that gets printed is completely arbitrary. It is a result of undefined behavior, because b remains unassigned.
You need to check that the user has entered a value before proceeding. scanf returns the number of items that it has processed, so your code should not use the value unless scanf has returned 1, indicating that one item has been read successfully:
int b;
for (;;) { // Repeat forever
int numRead = scanf("%d",&b);
if (numRead == 1) {
// We've got our number; end the loop:
break;
}
printf("You did not enter a number\n");
// Consume the data that cannot be interpreted as a number.
// Asterisk means "discard the value":
scanf("%*s");
}
printf("b=%d\n", b);
Demo.
If you try the following modification, you might get some insight:
#include<stdio.h>
int main()
{
int a, b;
a = scanf("%d",&b);
printf("%d %d",a,b);
}
When you type anything other than an integer, scanf returns 0, meaning that none of the items in the argument list was successfully filled. That means b has whatever value it had before the call to scanf. Since b is never initialized, this value is undefined.
P.S. Your main function should return type int, not void.
Why is & used here before decks (scanf("%i", &decks))?
And if my input is any letter like 'k' then it shows an output like "1929597720". Why?
#include <stdio.h>
int main(){
int decks;
puts("enter a number of decks:");
scanf("%i", &decks);
if (decks<1) {puts("Please enter a valid deck number");
return 1;
}
printf("there are %i cards\n", (decks*52));
return 0;
}
& before a variable name means "use the address of this variable". Basically, you're passing a pointer to decks to scanf()
As for what happens when you enter "k" (or other invalid input) - scanf() is failing, and you're seeing whatever random data was already in decks (which was never initialized).
To avoid this, check the return value of scanf(), and initialize decks.
int decks = 0, scanned;
puts("enter a number of decks:");
int scanned = scanf("%i", &decks);
if ((scanned < 1) || (decks < 1)) {
puts("Please enter a valid deck number");
return 1;
}
When passing stuff to scanf(), you need to pass in a pointer to the variable, not the variable itself. The & means "Don't take the variable, take the place in memory where this variable is stored." It's a little complicated, but it's necessary so that C can change the value of the variable.
Also, change your format string to
scanf("%d", &decks);
The garbage is because you don't initialize decks. If you put in int decks = 0, you would always get 0.
As every good C tutorial will teach you, the & sign is for getting a variable's address.
In the case of scanf(), this is necessary in order to tell scanf() where to put the requested data.
If you input a letter like k, or any non-number, scanf() will be disturbed by that, and if you would check scanf()'s return value, it would tell you that 0 items are read instead of 1.
In that case, the content of the given variable is unchanged and contains random garbage. And this is as well what you output.