0

我正在学习 C 中的数据结构,我需要从用户那里获取输入。我从搜索其他 stackoverflow 问题中了解到,在打印某些内容后需要使用 fflush。

我遇到的问题是,当我输入 add 时,它不会打印任何内容,直到我通过输入 quit 两次来中断 while 循环。有人可以解释如何解决这个问题以及为什么会发生吗?

这是代码:

#include "stdio.h"

typedef struct S_RacingCar {
    char name[8];
    int speed;

} RacingCar;

const int MaxCars = 4;

void PrintList() {
    printf("List Print...\n");
}

int AddCar(RacingCar *car) {
    printf("Enter Name And Speed:\n\n");
    char input[16];
    fgets( input, 15, stdin);
    int ok = 0;

    int result = sscanf(input, "%s %d", car->name, car->speed);

    if (result == 2) {
        ok = 1;
        printf("Added:%s Speed:%d\n\n", car->name, car->speed);
        fflush(stdout);
    } else {
        printf("Sorry, error parsing input\n\n");

    }

    return ok;
}
int main() {

    RacingCar allCars[MaxCars];
    int numCars = 0;

    char command[16];
    char input[16];

    while( fgets(input, 15, stdin) ){

        sscanf(input,"%s",command);

        if ( strncmp(command, "quit", 4) == 0){
            printf("\n\nBreaking...\n");
            break;
        } else if ( strncmp(command, "print", 5) == 0){
            PrintList();
            fflush(stdout);
        } else if ( strncmp(command, "add", 3) == 0){
            if (numCars < MaxCars) {
                numCars += AddCar( &allCars[numCars] );
                fflush(stdout);
            } else {
                printf("Sorry List is Full!!\n\n");
            }

        }
        fflush(stdout);


    }

    return 0;
}

我输入 print 后得到的输出,然后添加是:

print
List Print...
add

光标在添加下闪烁。如果我输入退出,我会得到:

print
List Print...
add
quit
Enter Name And Speed:

Sorry, error parsing input

所以程序还没有结束,我想知道为什么。有人可以解释一下吗?要结束程序,我必须再次输入退出:

print
List Print...
add
quit
Enter Name And Speed:

Sorry, error parsing input

quit


Breaking...
<<< Process finished. (Exit code 0)
================ READY ================
4

2 回答 2

2

你的程序表现怪异的原因是它表现出 UB。

改变

int result = sscanf(input, "%s %d", car->name, car->speed);

int result = sscanf(input, "%s %d", car->name, &(car->speed));

这样做是因为sscanf期望 anint*但你给它一个int.

此外,您还可以添加

setvbuf(stdout, NULL, _IONBF, 0);

在开始main并删除fflush()程序中的所有内容。stdout上面的行在写入时刷新。

于 2015-01-25T05:50:45.797 回答
0

除了其他答案,更改:

int AddCar(RacingCar *car) {
  printf("Enter Name And Speed:\n\n");

至:

int AddCar(RacingCar *car) {
  fflush(stdout);
  printf("Enter Name And Speed:\n\n");
于 2015-01-25T05:52:45.763 回答