简体   繁体   中英

scanf and printf for loop different amount of output

THe error I get is that the scan will take one more digit than the print loop. I have example code after the loops. Would anyone know why that is?

   int main( int argc, char *argv[] ) {

        //Throw error is *Argv[] is not an integer
        //assuming it was an integer
        int cnt = (int)(argv[1][0] - '0');
        printf( "number is %d\n", cnt );
        //
        printf("Enter %i integer values to place in tree:\n", cnt);
        for ( i1 = 0; i1 < cnt; ++i1) {
                scanf( "%d\n", &elemArray[i1] );
        }

        //first ouput "INput Values"

         for ( i2 = 0; i2 < cnt; ++i2) {
               printf( "%d\n", elemArray[i2] );
        }

        //Build tree with each element
        return 0;
}

Ouput is:

Enter 5 integer values to place in tree:
1
2
3
4
5
6
1
2
3
4
5

I figured it out. It was scanf( "%d\\n", &elemArray[i1] ); to be changed to scanf( "%d", &elemArray[i1] );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM