不打印最后一个字符:仅在下一个输入后打印

时间:2021-04-07 10:23:05

标签: c buffering

我遇到一个问题,当我尝试打印输入时,程序不会打印最后一个字符串(在本例中为 var_quantita)。

但是如果我添加一个 \n,或者如果我从 stdin 发送另一个命令,它会起作用。

所以我认为问题与最后一个字符串有关,但我不确定。

我的代码:

uint32_t var_quantita;
uint8_t var_tipo[BUF_SIZE];
//...
memset(com_par, 0, BUF_SIZE);
memset(comando, 0, BUF_SIZE);
memset(arg2, 0, BUF_SIZE);
memset(arg3, 0, BUF_SIZE);
memset(arg4, 0, BUF_SIZE);

//prendo in ingresso il comando e i parametri
fgets(com_par, BUF_SIZE, stdin);

sscanf(com_par, "%s %s %s %s", comando, arg2, arg3, arg4);
printf("Argomenti inviati:%s %s %s %s \n", comando, arg2, arg3, arg4);

//......

if(strcmp(comando, "add\0") == 0){

    strcpy(var_tipo, arg2);
    var_quantita = atoi(arg3);
    printf("Tipo:%s\nQuantita:%d", var_tipo, var_quantita); 


}//fine if(add)

1 个答案:

答案 0 :(得分:1)

您系统的缓冲设置为行缓冲,当遇到换行符时,字符作为一个块从缓冲区传输。使用 \n 是完全有效的,但它也有打印换行符的副作用,还有其他选项,即:

  • fflush(stdout) 之后使用 printf 将刷新缓冲区,无需考虑 \n

  • 您可以将缓冲模式更改为无缓冲,尽快写入每个输出。同样,不需要 \n

    setvbuf(stdout, NULL, _IONBF, 0);