-3
#include <stdio.h>

int main(){
    int l,m,q,j;
    char option;
    scanf("%d",&q);
    printf("%d\n",q);
    for(j=0;j<q;j++){
        scanf("%c %d %d",&option,&l,&m);
        printf("%c %d %d",option,l,m);
    }
    return 0;
}

Output:

3(Input)
3
C 1 4(Input)

 0 -374066224C 1 4

What is wrong with the above code? It is not giving the expected output.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
sachin irukula
  • 12,841
  • 4
  • 19
  • 19

2 Answers2

9

There is still a newline character in the input stream from the initial scanf() (and subsequent scanf()s): this will be assigned to option and the subsequent int assignments will fail as C is not an int, meaning l and m are uninitialised int variables.

To skip it add a leading space character to the format specifier of the scanf() within the for loop:

scanf(" %c %d %d",&option,&l,&m);
    /* ^ */

The return value of scanf() is the number of successful assignments made: check it to ensure 3 assignments are made.

if (3 == scanf(" %c %d %d",&option,&l,&m))
{
    /* Valid input. */
}
hmjd
  • 120,187
  • 20
  • 207
  • 252
  • That solved the problem but could you explain why there is a newline character please – sachin irukula Aug 10 '12 at 13:27
  • @sachinirukula, when the user enters the number they type `3` and hit return. The return inserts a new line character into the input stream. The new line character is not consumed by the `scanf()`, leaving it in the input stream. – hmjd Aug 10 '12 at 13:28
  • @sachinirukula The reason why goes back to the ancient things called typewriters. When you pressed their equivalent to enter, the machine did a carriage return (back to the left-most side of the paper) and then it changed to a new line. Windows works the same. Windows text files even end each row with the ASCII symbols '\r' (ASCII 13) '\n' (ASCII 10), they are called carriage return and line feed respectively. – Lundin Aug 10 '12 at 13:33
  • 2
    For the record, the reason why the initial space solves the problem is this section of the standard: 7.21.6.2/5 (scanf functions) "A directive composed of white-space character(s) is executed by reading input up to the first non-white-space character (which remains unread), or until no more characters can be read. The directive never fails." – Lundin Aug 10 '12 at 13:34
2

Every time you prompt the user for an input, they will write it and then press enter. Enter leaves a line feed character in the input buffer. You must discard it before asking for a character input, or it will end up in your character variable.

The easy but blunt solution is this:

scanf("%d",&q); getchar();
printf("%d\n",q);
for(j=0;j<q;j++){
    scanf("%c %d %d",&option,&l,&m); getchar();
    printf("%c %d %d",option,l,m);
}

(I'm pretty sure there is a C FAQ for this somewhere but I can't find the link.)

Lundin
  • 195,001
  • 40
  • 254
  • 396