Yahoo Interview Question
Country: United States
how to make it behave in a normal manner so that when the input is given in the form of a string:
"1,2,3,4,5,6,7,8,9"
i can use the above method to store the numbers in an array
int ar[10];
ar[0]=1
ar[1]=2
ar[2]=3
:
:
: so on.......
- scanf() blocks when called the first time, but does not block after that
if scanf() is given invalid input, it does not advance the pointer in its internal buffer, hence the buffer remains what was earlier (9 in this case) , which keeps on getting printed.
- you can check if scanf() returned > 0 in the while condition. This will allow scanf() to function normally
(1)first of all you must know how while loop works..
intialisation;
while(check condition)
{
increment;
}
(2) scanf() always return no. of fields it reads. so in your first case ..
while(scanf("%d,",&a))
{
//store a as you wish to
printf("%d ",a);
}
here output will be 1 2 3 4 5 6 7 8 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9..........run time error.
so what happened is scanf always return no. of fields so up to 9 it was returning value 1.but after that there is no input so scanf returns wierd values like -124689234 etc..,,,but remember our variable a still has value 9 .so as simple as this it behave like this
(1)first of all you must know how while loop works..
intialisation;
while(check condition)
{
increment;
}
(2) scanf() always return no. of fields it reads. so in your first case ..
while(scanf("%d,",&a))
{
//store a as you wish to
printf("%d ",a);
}
here output will be 1 2 3 4 5 6 7 8 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9..........run time error.
so what happened is scanf always return no. of fields so up to 9 it was returning value 1.but after that there is no input so scanf returns wierd values like -124689234 etc..,,,but remember our variable a still has value 9 .so as simple as this it behave like this
(1)first of all you must know how while loop works..
(2) scanf() always return no. of fields it reads. so in your first case ..
here output will be 1 2 3 4 5 6 7 8 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9..........run time error.
- Anonymous August 14, 2014so what happened is scanf always return no. of fields so up to 9 it was returning value 1.but after that there is no input so scanf returns wierd values like -124689234 etc..,,,but remember our variable a still has value 9 .so as simple as this it behave like this