C Programming - Input / Output - Discussion

Discussion Forum : Input / Output - Point Out Errors (Q.No. 2)
2.
Point out the error in the program?
#include<stdio.h>

int main()
{
    char ch;
    int i;
    scanf("%c", &i);
    scanf("%d", &ch);
    printf("%c %d", ch, i);
    return 0;
}
Error: suspicious char to in conversion in scanf()
Error: we may not get input for second scanf() statement
No error
None of above
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
23 comments Page 1 of 3.

Shiv Bhajan said:   1 decade ago
Why it will not get input for the second scanf () ? please Explain it.

Pratham said:   1 decade ago
You will not get a chance to supply a character for 2nd scanf().

NITESH KHATRI said:   1 decade ago
Because this is the peculiarity of scanf(). After supplying data for the int i variable we would hit the enter key. What scanf() does it assigns the value what we gave to the variable i and keeps the enter key unread in the keyboard buffer (standard i/o buffer) , so when its time to supply another value the 2nd scanf() statement will read the enter key from the buffer thinking that user has entered the enter key. To AVOID this problem. WE USE THE FUNCTION flush (stdin). It is designed to remove or 'flush out' any data remaining in the buffer.

Khushi said:   1 decade ago
No its not the case.

It will take input but the values that will get stored will be unexpected and it may lead to segmentation fault as well.

Shoana Carvalho said:   1 decade ago
What I guess is segmentation fault occurs only when there is buffer overflow comes into existence because of too many function calls!

Rup said:   1 decade ago
'i' is an integer type so %d should be used and 'ch' is a character type so %c or %s should be used.

Himanshu Bansal said:   1 decade ago
You can store the character value inside integer value because character is of 1 byte and integer is 2 byte but you can not store integer value inside character value.

Nilay Vishwakarma said:   1 decade ago
@Khushi.
There can't be any segmentation fault in this program
ch would store ASCII 10 (return or line feed).

Try cleaning buffer before entering next value since <return> would be in buffer and gets stored in next scanf.

@Himanshu Bansal.
Your point is almost correct, theoretically. However,we can store integer value inside character value, but there would be a slight ,malfunction. The least significant bits of the integer would be accepted as character.

@Rup.
The apple has fallen very far dude.

Dinesh said:   1 decade ago
I executed this program in Dev c++.

int main()
{
char i;
scanf("%d",&i);
printf("i==%c",i);
getch();
return 0;
}

Program compiled and executed successfully (Without any warning and errors).

Input provided : 65
Output : i==A

Shivi said:   1 decade ago
Because %d is a format specifier of int type but ch is a char data type.


Post your comments here:

Your comments will be displayed after verification.