代码之家  ›  专栏  ›  技术社区  ›  Mattia Surricchio

scanf和printf未按顺序执行

  •  -2
  • Mattia Surricchio  · 技术社区  · 6 年前

    我正在编写一个简单的代码来获取用户的输入。这是我的代码:

    int main() {
    
        char *start = NULL;
        char *end = NULL;
        char in, out, shift;
    
        while (strcmp(start, "acc") != 0) {
            printf("before start");
            scanf("%ms ", &start);
    
            if(strcmp(start, "acc") != 0) {
                printf("in if");
                scanf("%c %c %c %ms", &in, &out, &shift, &end);
                printf("%s", start);
                printf("%c", in);
                printf("%c", out);
                printf("%c", shift);
                printf("%s", end);
            }
        }
    }
    

    输入总是这样:

    string char char char string
    

    使用任意长度的第一个和最后一个字符串(这就是我使用 %ms )

    代码运行良好,可以做它必须做的事情,唯一的问题是我想检查 start 字符串等于 acc ,如果是,请跳过这些代码行。

    当我插入 行政协调会 进入我的 scanf("%ms ", &start); 我按enter键,我的代码仍然等待所有其他输入被插入,一旦它们全部插入,它就会检查所有条件,生成所有打印,然后结束。

    怎么了?

    1 回复  |  直到 6 年前
        1
  •  2
  •   user3121023    6 年前

    使用未初始化的指针 start ,do/while循环更适合在使用 strcmp .
    我不确定 %ms 为每个调用分配一个新缓冲区。由于缓冲区不需要初始化,我怀疑它分配了一个新的缓冲区。为了避免内存泄漏, free 缓冲区在需要之前和不再需要之后。
    后面的空间 %质谱 将使用所有尾随空白。要终止扫描,必须输入一些非空格。把后面的空格移到下一个 scanf 在第一次之前 %c

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    int main() {
    
        char *start = NULL;
        char *end = NULL;
        char in, out, shift;
    
        do {
            if ( start) {
                free ( start);
                start = NULL;
            }
            printf("before start: ");
            fflush ( stdout);
            scanf("%ms", &start);
    
            if(strcmp(start, "acc") != 0) {
                if ( end) {
                    free ( end);
                    end = NULL;
                }
                printf("in if: ");
                fflush ( stdout);
                scanf(" %c %c %c %ms", &in, &out, &shift, &end);
                printf("%s", start);
                printf("%c", in);
                printf("%c", out);
                printf("%c", shift);
                printf("%s", end);
            }
        } while ( strcmp(start, "acc") != 0);
    
        if ( start) {
            free ( start);
            start = NULL;
        }
        if ( end) {
            free ( end);
            end = NULL;
        }
    
        return 0;
    }