unexpected result when i entered character instead of integer value in scanf - c

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.

Related

How does a scanf() inside printf() work?

#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().

integer validation gives infinite loop

The user needs to type an integer, then type enter. If it gets validated then it should return the integer, if not validated the user should get an error message.
When I try to validate input through getInt() function, I get an infinite loop when I type 1 or more chars. When I type abc, I get an infinite loop of error messages, while entering 1a gets the correct validation (1 single error message). I followed the directions of this flowchart:
Code
#include <stdio.h>
void clrKyb(void){
char input;
do {
scanf("%c",&input);
} while(input !='\n');
}
int getInt(void){
char NL= 'x' ;
int value ;
while(NL!='\n'){
scanf("%d%c",&value,&NL);
if(NL!='\n') {
void clrKyb(void);
printf("Invalid integer, please try again:");
}
}
return value ;
}
int main(void) {
int iVal;
printf("Enter an integer: ");
iVal = getInt();
printf("You entered: %d\n", iVal);
return 0;
}
As noted in comments:
cxw said:
In getInt, void clrKyb(void); should just be clrKyb();, since you are wanting to use the clrKyb you have already defined.
Jonathan Leffler said:
Note that in clrKyB() (and getInt()), you need to check the return value from scanf(). If it returns EOF, then no amount of retrying etc is going to stop an infinite loop. (As cxw notes, in getInt() at the moment, you (re)declare clrKyB() and don't call it — that's also a problem.)

printf after scanf always displays 1 (same unexpected value)

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.

Using Scanf after getchar?

I am taking C programming course. I did not understand these codes.
#include <stdio.h>
int main()
{
int c;
int ival;
printf("type : ");
c = getchar();
scanf("%d", &ival);
printf("c = %d\n", c); //65
printf("ival = %d\n", ival); //127
return 0;
}
For example whenever I type Abc, I am getting c = 65; ival = 1.
why ival is 1?
ival is never initialized, so it can have any value. The reason is that, c is receiving 'A' (through getchar()) and then scanf fails to read a number (since the next character in the input, 'b', is not a decimal number), so it never touches ival.
You can check the return value of scanf to see if it fails or succeeds:
if (scanf("%d", &ival) != 1)
printf("you need to enter a number\n");
else
printf("entered: %d\n", ival);
Note that scanf returns the number of items it successfully read and assigned. For example scanf("%d %f %c", ...) would return 3 if all three items were correctly read.1
1Note that assigned means that ignored input (such as those with the assignment-suppresion modifier (*)) doesn't count towards the return value of scanf (C11, 7.21.6.2.10,16). Furthermore, %n doesn't affect the return value of scanf (C11, 7.21.6.2.12).
With Abc, getchar() will read A, thus, c will hold the character code for A, which happens to be 65 on your machine (this is the ascii code for A).
For ival, you can get anything: since %d on scanf() expects to read an integer, and you didn't provide one, scanf() returned prematurely, leaving bc in the input buffer, so the value you read from ival when you call printf() is undefined: it can print anything.
The reason is that your program invokes undefined behavior.A is read by getchar while bc is left unread by scanf because %d expects to read an integer and hence on encountering the character it stop reading immediately and leave ival uninitialized.

passing value obtained in one function to another function. C language

I am writing a program, that is encrypting a number, entered by user. Encryption steps are performed by functions, which I have to write. The problem is that I have to use value obtained in one function, in the next function. Here is what I am trying to do:
first function reads an integer. second adds 4 to every digit of that integer. and the problem is that how to use the integer that is entered in the first function, in the second function.
void input(int *num)
{
int numin;
printf("Please enter an integer greater than 99999: ");
scanf("%d", &numin);
while (numin<99999)
{
printf("Incorrect input.\n");
printf("Please enter an integer greater than 99999: ");
scanf("%d", &numin);
}
num=&numin;
printf("The number entered is %d\n", numin);
return;
}
int add4(int num)
{
int a,b=1,numplus4;
int i=-1;
for (numplus4=0; b==0;)
{
a=num%10;
b=num/10;
num=b;
a+=4;
if (a>9)
a-=10;
i++;
numplus4+=a*pow(10, i);
}
num=numplus4;
printf("%d\n", num);
return num;
}
I have googled on this topic: but all i got didnot help me, most of answers are for Javascripts, but I am using C.
You are not actually returning anything from the input function.
Instead of passing a pointer to the number being set (which you do not set correctly) you should use the return statement to return the value:
int input(void)
{
...
return numin;
}
Then you can use it as this:
int main(void)
{
int result = add4(input());
printf("Result is %d\n", result);
return 0;
}
The reason you don't return anything in your current function, is because in the input function the parameter num is local to that function. So any changes you made to it (like assigning to it) is lost when the function return.
What you are doing is potentially dangerous as it borders on undefined behaviour. You want to make the pointer point to a local variable, but when the function returns the memory where that local variable is stored is no longer valid to access.
You can use pointer arguments to return values though, this is what is called passing arguments by reference. But you don't assign pointer like you do, instead you use the dereferencing operator (unary *):
*num = numin;
For it to be valid though, you have to pass the address of an already allocated variable, like this:
int num;
input(&num); /* Use the address-of operator to create a pointer */
However, I suggest using the solution in the first part of this answer, until you know more about pointers and how they work.
You have to dereference the pointer in order to save the inputted value to the memory location pointed to by the pointer:
void input(int* num) {
int numin;
printf("Please enter an integer greater than 99999: ");
scanf("%d", &numin);
while (numin<99999)
{
printf("Incorrect input.\n");
printf("Please enter an integer greater than 99999: ");
scanf("%d", &numin);
}
printf("The number entered is %d\n", numin);
*num=numin; // <-- This line needs the '*' at the beginning
}
The value obtained in one function can be used in the another function if the variable is declared as static variable.

Resources