printf的statments为了不打印

printf的statments为了不打印

本文介绍了printf的statments为了不打印的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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\n"); //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\n");
    printf("2. Delete\n");
    printf("3. Print\n");
    printf("4. Find\n");

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

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

当我编译和执行,我可以给输入,但printf的语句的顺序都没有先后顺序。举例来说,这是我得到的输出后,我给输入和输入数据。

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

我尝试添加fflush(标准输出),与printf说明书之后也是如此。

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

推荐答案

删除 \\ n 从最初的 scanf函数

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

那是什么 \\ n 在那里做什么?这是什么原因造成你的 scanf函数来苟延残喘,等待而不是立即终止额外的输入。

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

这是 \\ n scanf函数特殊的意义。当您使用空白字符(空格,制表或 \\ n )的 scanf函数格式说明,你是明确要求 scanf函数跳过所有空白。如果这样的字符在 scanf函数格式字符串的最末尾处,然后读取实际数据后, scanf函数将继续等待输入直到遇到一个非空白字符。这是你的情况究竟会发生什么。

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.

这篇关于printf的statments为了不打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 03:16