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:
24 comments Page 2 of 3.

Nidipa said:   9 years ago
Here they did not flush the buffer, so it can not ready to get the next input.

When I tried the code using the following method:
scanf("%c\n", &i);
scanf("%d", &ch);
printf("%c %d", ch, i);

It gets the two inputs from the user.

Afzal said:   10 years ago
@Nitesh Khatri. I understood your explanation.

But, is Shivam's explanation is right?

Does it depend on the Type of data ?

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

Ivon said:   1 decade ago
But why I use CodeBlock (GCC compiler) to get it compiled and each scan runs smoothly, just getting wrong value, but it just got value for each place!

Shivam said:   1 decade ago
Nice question!

[B]. Error: We MAY not get input for second scanf() statement.

"may".

-If you enter a character for first scanf, you are allowed to enter a value for second scanf.

-If you enter an integer for first scanf, you are not allowed to enter a value for second scanf.

Answer is simple just try think harder in memory size differences between int and char :).

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

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

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.

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.

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.


Post your comments here:

Your comments will be displayed after verification.