Search code examples
cstringinputscanfgets

scanning string in c


   int main( )
    {
        char str[200];
        int n,tc;
        scanf("%d",&tc);
        while(tc--)
         {
           scanf("%d",&n);
           gets(str);
           puts(str);
        }
    return 34;
    }

Why this code is not scanning no. of strings(str) equals to tc?
Platform UBUNTU 10.04


Solution

  • Lets break down the code one line at a time (more or less):

    scanf("%d",&tc);
    

    reads an integer into tc.

    while(tc--)
    

    loops tc times

        scanf("%d",&n);
    

    reads an integer into n

        gets(str);
    

    reads the rest of the line into str, removing the trailing newline

        puts(str);
    

    prints out the string, followed by a newline

    So you're reading an integer, and then reading that many integer+rest of line pairs and printing out the lines (but not the integers -- they get thrown away). Reading an integer involves skipping any blank space (spaces, tabs, and entire blank lines) before the integer but not any after it, so this can be a little confusing, depending on what kind of input you're feeding to the program.

    In your example, you say you're feeding it the input:

    3
    4
    anil kuma
    2
    abc
    4
    ams
    

    So lets go through the program and see what it does:

    • read the integer 3 into tc
    • loop 3 times
    • (first loop)
      • read 4 into n
      • read the rest of the line (blank) into str,
      • print the blank line
    • (second loop)
      • try to read an integer into n, but the input (anil kuma) isn't an integer, so sets the error flag on stdin
      • read the rest of the line (anil kuma) into str
      • prints anil kuma
    • (third loop)
      • read 2 into n
      • read the rest of the line (blank) into str
      • print the blank line
    • loop is done, return exit code 34.

    You never check the return value of functions or the error code on stdin, so the fact that you got an error trying to read an integer on the second iteration is completely invisible.

    You might get an output more like what you are expecting by changing your scanf calls to:

    scanf("%d ", &n);
    

    Note the extra space after the %d conversion, which causes scanf to read and throw away whiltespace until it finds a non-whitespace character. This will cause it to throw away the newlines after the integers, as well as any following blank lines and any spaces/tabs at the beginning of the next non-blank line