Printf statments not printing in order

后端 未结 2 686
甜味超标
甜味超标 2020-12-12 07:27
typedef struct node_s{
int data;         
struct node_s *next;
}node_t;                

void insert(node_t *pointer, int data){
     while(pointer->next != NULL)         


        
相关标签:
2条回答
  • 2020-12-12 08:13

    In addition to removing \n from your scanf statements, be aware that scanf will read the data from the command line, filling the variable specified, but it will leave the \n in the input buffer causing problems the next time scanf is called. Since there is no standard command to flush input buffers, you are responsible for insuring that you do not have extraneous unused characters in the input buffer the next time scanf is called. One simple way to handle manually flushing the input buffer after each scanf if to simply use getchar() to read any remaining characters in the input buffer until \n is encountered. For example:

    int c;
    ...
    scanf ("format", &var);
    do {
        c = getchar();
    while ( c != '\n' );
    

    This will insure subsequent calls to scanf retrieves the wanted data instead of passing the characters that remain in the input buffer.

    0 讨论(0)
  • 2020-12-12 08:29

    Remove \n from the very first scanf

    scanf("%d\n", &input);
    

    What is that \n doing there? That is what is causing your scanf to "linger", waiting for extra input, instead of terminating immediately.

    That \n has special meaning for scanf. When you use a whitespace character (space, tab or \n) in scanf format specifier, you are explicitly asking scanf to skip all whitespace. If such character is used at the very end of scanf format string, then after reading the actual data scanf will continue to wait for input until it encounters a non-whitespace character. This is exactly what happens in your case.

    0 讨论(0)
提交回复
热议问题