使用C编程语言中scanf的返回值作为检查

Chr*_*_45 2 c validation input

你如何使用scanf的返回值来确保它是我得到的双倍?

double input;

do {  /* do this as long as it not a double */
  printf("Input?");
  scanf("%lf", &input);
} while(scanf("%lf", &input) != 1); /* this will not work */
Run Code Online (Sandbox Code Playgroud)

Jaa*_*koK 5

scanf将返回分配的项目数.在您的情况下,由于格式字符串仅包含%lf,它将1完全返回您获得的格式字符串double.您的代码的问题是您首先scanf在循环内部调用,这将读取double流.然后,在你的while情况下,你scanf再次打电话,但没有其他double人阅读,所以scanf没有做任何事情.

我编写代码的方式就像

int no_assigned;
do {
    printf("Input?");
    no_assigned = scanf("%lf", &input);
} while (no_assigned != 1);
Run Code Online (Sandbox Code Playgroud)

额外的变量就在那里,因为我觉得scanf它应该是循环内部的代码,而不是while条件,但这确实是个人偏好; 您可以消除额外的变量并移动(注意,移动,而不是复制)scanf条件内的调用.

编辑:这是使用fgets它的版本可能更好:

double input;
char buffer[80];

do {
    printf("Input? ");
    fflush(stdout); // Make sure prompt is shown
    if (fgets(buffer, sizeof buffer, stdin) == NULL)
        break; // Got EOF; TODO: need to recognize this after loop
    // TODO: If input did not fit into buffer, discard until newline
} while (sscanf(buffer, "%lf", &input) != 1);
Run Code Online (Sandbox Code Playgroud)