Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
486 views
in Technique[技术] by (71.8m points)

c - Printf statments not printing in order

typedef struct node_s{
int data;         
struct node_s *next;
}node_t;                

void insert(node_t *pointer, int data){
     while(pointer->next != NULL){     
           pointer = pointer->next;     
     }                                 
     pointer->next = (node_t *)malloc(sizeof(node_t));
     pointer       = pointer->next;                   
     pointer->data = data;                            
     printf("Elemnet inserted
"); //2. Followed by this statment once done.                      
     pointer->next = NULL;                            
}
int main(){                        
    node_t *start, *temp;          
    start      = (node_t *)malloc(sizeof(node_t));
    temp       = start;                           
    temp->next = NULL;                            
    printf("1. Insert
");
    printf("2. Delete
");
    printf("3. Print
");
    printf("4. Find
");

    while(1){
     int input;
     scanf("%d
", &input);

     if(input==1){
        int data;
        printf("Input data
");//1. I want this to print out first once I give 1 input.
        fflush(stdout);
        scanf("%d", &data);
        insert(start, data);
     }
    }

When I compile and execute, I can give inputs but the order of printf statements are not in sequence. For instance, this is how I get the output after I give input and enter the data.

sh-4.1$ ./linked_list
1. Insert
2. Delete
3. Print
4. Find
1
23
Input data
Elemnet inserted
1
45
Input data
Elemnet inserted

I tried adding fflush(stdout), after the printf statment as well.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Remove from the very first scanf

scanf("%d
", &input);

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

That has special meaning for scanf. When you use a whitespace character (space, tab or ) 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...