只要输入有效,就继续运行程序

时间:2020-02-13 04:31:12

标签: c loops while-loop

因此,我刚刚开始学习编程,并且正在研究一个简单的程序,该程序会扫描并存储用户输入值,只要它是有效的浮点数即可。如果输入无效,则程序将立即退出并返回1。最后,如果所有输入均有效,则程序将输出存储的值。我在想像

这样的结构
while (scanf("%f",input)==1){
    //code that store the value of input;
    value=input
}
else{
    printf("invalid");
    return 1
}
printf("%f",value);

但是问题是,不存在While-else结构,而我真的很难解决这个问题。我可以对输入进行任何其他条件处理以产生期望的结果吗?

顺便说一句,我认为仅删除else并不能真正起作用-因为要输出值,我必须使用Ctrl d来手动退出while循环。然后,因为我退出了while循环,所以无论如何我都将打印无效。是否存在仅打印值的结构?谢谢。

3 个答案:

答案 0 :(得分:0)

while循环将一直持续运行直到达到退出条件为止,这意味着不需要else,因为下面的代码将不被执行。

对此的一个简单解决方法是删除else,因为不需要它:)

答案 1 :(得分:0)

while谓词必须为假才能继续,因此假设的while-elsewhile相同。一个人想在sscanf的三个结果之间做出决定(至少):

  • 已完成对浮动的处理;
  • 错误处理(这可能是基础流错误或语法错误);
  • stdin的文件结尾)

sscanf documentation中,可以使用此设置,

#include <stdlib.h>
#include <stdio.h>

int main(void) {
    float input, value;
    int nread;
    while((nread = scanf(" %f", &input)) == 1) {
        ////code that store the value of input;
        value=input;
    }
    if(ferror(stdin)) {
        // nread != 1 && ferror: error reading input.
        perror("stdin"); // POSIX.1-2017 guarantees this will be set, not C99.
        return EXIT_FAILURE;
    } else if(nread != EOF) {
        // nread != 1 && nread != EOF && !ferror: matching error.
        fprintf(stderr, "Syntax error.\n");
        return EXIT_FAILURE;
    }
    // nread == EOF && !ferror: normal, input ends before the first conversion has
    // completed, and without a matching failure.
    return EXIT_SUCCESS;
}

sscanf的返回值包含更多信息,而只是一个二进制决定,因此,通常来说,要保存它。

答案 2 :(得分:-1)

我猜您的代码在一个函数中,并且您想在输入错误的情况下从那里返回,因此在这种情况下这将起作用

while(1) {
    //code that store the value of input;
    if (scanf("%f",input)==1){
      value=input
    }
    else{
      return 1;
    }
}