繁体   English   中英

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

[英]Using the return value from scanf in the C programming language as a check

你如何使用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 */

scanf将返回分配的项目数。 在您的情况下,由于格式字符串仅包含%lf ,因此在您获得double的情况下,它将完全返回1 您的代码的问题是您首先在循环内调用scanf ,这将读取流中的double 然后,在你的while条件下,你再次调用scanf ,但是没有另一个要读取的double ,所以scanf什么都不做。

我编写代码的方式就像

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

额外的变量是因为我感觉像scanf是应该在循环内部的代码, while不是在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);

scanf()和朋友返回成功匹配和分配的输入项的数量。 没有与类型相关的信息。 但是既然你已经在转换字符串中指定了lf ,那么你会得到一个双倍 - 我想我错过了你的观点。

就像迈克尔所说,scanf()返回和整数,表示suceccesfully读取的元素数量。 据我可以从联机帮助页中看到,您无法使用返回值来验证读取的内容是否为double。

我想这就是你要做的事情:

double input;

do {  /* do this as long as it not a double */
  printf("Input?");
} while(!scanf("%lf", &input));

scanf()将返回给定/提供的输入数。 它不会返回任何与数据类型相关的结果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM