0

[Solved]Strange behavior of scanf in c language

I made a program which takes int inputs until you enter 1 and prints total number of inputs you've entered. This works fine. Ie for 3 4 1 output is 3, for 5 4 6 7 1 output is 5 ... https://code.sololearn.com/cEaA4MW1703u/?ref=app [code 1] But when I made same program to take char inputs until you enter 'a', gives totally wrong answer. Ie. For g h a output is 5 , for k f h r d a output is 11.. https://code.sololearn.com/c2ChayXblY61/?ref=app [code 2] But more strange thing happens when I combine both programs in one, the output of char inputs is still wrong and it don't even match with previous program's [code 2] output when given same inputs. Ie for 3 4 1 g h a output is 3 int and 6char for 5 4 6 7 1 k f h r d g output is 5 int and 12char https://code.sololearn.com/cpqNJtHXcIT0/?ref=app [code 3] Now if I make same program in c++ (by changing scanf printf with cin cout) Program works just fine. https://code.sololearn.com/c3Jtcbh2Y9Ru/?ref=app [code 4] What's wrong? What am I missing?

22nd Feb 2021, 8:45 AM
Yugal Kishore
3 ответов
+ 7
(Same answer as visph ) The second code is counting the spaces/newlines in the input also. This is because an integer can be of any length, and so for integers, space/newline is taken as a delimiter which denotes the end of the integer. But a char is always of length 1 and that is why you don't need to have whitespace as delimiters in the case of chars, and for the same reason, whitespace is taken in as input and are counted by your code. If you're sure that the separator will be a space, you can change the format string passed into scanf() to "%c " (%c followed by a space). This will output 4 for the input `d c b a` Or, you can simply pass the input like this withtout changing the string dcba It works in C++, because as far as remember (someone correct me if I'm wrong), `cin` always takes whitespace as a delimiter. It doesn't matter if you take int, char or even string input, when you encounter a whitespace, cin will stop taking input for that variable.
22nd Feb 2021, 9:08 AM
XXX
XXX - avatar
+ 6
it seems that input are not handled the same manner in c and c++ in c, char input consume only one char, so if you separate char by space you'll get twice the count-1 as you're counting spaces... in c++, char input consume one char (input) plus all next spaces... so you've got correct count with or without spaces ^^
22nd Feb 2021, 9:00 AM
visph
visph - avatar
+ 1
Looks like problem is solved😁. visph XXX thanks for your answers.
22nd Feb 2021, 9:14 AM
Yugal Kishore