简体   繁体   中英

Output doesn't appear right away

/* Written by: Tai Ngo
   Date: 10/03/2012
   Description: This program allows the users to print numbers
   in the desired orders.
   Problem B
*/


#include <stdio.h>


int main (void)

{   //Global declaration
    int num1;
    int num2;
    int num3;
    int num4;
    int num5;
    int num6;
    int num7;
    int num8;
    int num9;
    int num10;

    //Statements
    printf("Enter 10 integers, separated by spaces:");
    scanf("%5d %5d %5d %5d %5d %5d %5d %5d %5d %5d ", &num1, &num2, &num3, &num4, &num5, &num6, &num7, &num8, &num9, &num10 );

    printf("%5d    %5d\n", num1, num10);
    printf("%5d    %5d\n", num2, num9);
    printf("%5d    %5d\n", num3, num8);
    printf("%5d    %5d\n", num4, num7);
    printf("%5d    %5d\n", num5, num6);

    return 0;
} //main

Why is that I have to type in some letter for the output to appear after I input integers?

If you want the numbers separated by spaces then you shouldn't be asking for spaces after the last number. I would get rid of all the spaces in your scanf format; they aren't necessary.

Also, it's a good idea to put fflush(stdout) between the printf and scanf calls, otherwise there is no guarantee that the user will see the print output before scanf tries to read.

A space ( ) in the scanf format tells scanf to read and discard whitespace characters (spaces, tabs, and newlines) until it gets a non-whitespace character and leave that non-whitespace character on the input (so its the next character read). Since your format string ends with a space, that's what scanf will do after it reads the 10 integers you asked it for.

If you get rid of that space, then scanf will return as soon as its read the 10th number and wont try to read anything after it, so you won't have to type another line (with something besides whitespace on it) to get the program to continue.

Since a %d specifier also skips any whitespace on the input before a number that it reads, all the rest of the spaces in the scanf format are redundant (and unneeded), but they don't actually cause any harm -- they just slow down the call by a miniscule unmeasurable amount.

Please remember when you add %5d in scanf it means you are asking the user to input each integer to have 5 digits

eg: 11111 22222 33333 44444 55555 66666 77777 88888 99999 12345

and if you don't want to restrict the user to 5 digits simply replace %5d to %d.... even eg: 1 2 3 12345 1223 123 122 333 444 11 22

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