c++ - 在c中使用scanf停止无限while循环?

标签 c++ c while-loop scanf

我创建了一个程序,它接受由注释分隔的 3 个数字,我将用它们来做一些计算。它将接受用户输入的这些数字,我使用 scanf 来接受它。

这是我到目前为止所拥有的:

#include <stdio.h>
#include <math.h>
#include <ctype.h>
#include <stdbool.h>

int main(void)
{
    float a, b, c;

    bool continue_program = true;

    while (continue_program) {
        printf("Enter your coordinates: ");
        scanf("%f,%f,%f", &a,&b,&c);
        if(isdigit(a) && isdigit(b) && isdigit(c)){
            printf("Success!");
        } else {
            printf("Try again!");
        }
    }
}

示例输出:

Try again!Enter your coordinates: Try again!Enter your coordinates: Try again!Enter your coordinates: Try again!Enter your coordinates: Try again!Enter your coordinates: Try again!Enter your coordinates: Try again!Enter your coordinates: Try again!Enter your coordinates: Try again!Enter your coordinates: Try again!

我知道其他人也遇到过同样的问题,并浏览了这些问题的答案,但无法让他们的实现适用于此代码。

最佳答案

你都错了 scanf() 将返回匹配的参数数量,而你没有检查它。

此外,isdigit() 函数采用整数,如果传递参数的 ascii 值对应于数字,则返回非 0

要使程序在满足条件时停止,您应该更改循环内的 continue_program 值,假设您想在 scanf() 没有满足时停止' t 读取 3 float ,它将返回一个与 3 不同的值,因此您可以将其设置为 if 条件

#include <stdio.h>
#include <math.h>
#include <ctype.h>
#include <stdbool.h>

int main(void)
{
    float a, b, c;

    bool continue_program = true;

    while (continue_program) {
        printf("Enter your coordinates: ");
        if (scanf("%f,%f,%f", &a, &b, &c) == 3){
            printf("Success!");
        } else {
            continue_program = false;
            printf("Try again!");
        }
    }
}

根据OP的评论建议使用此解决方案

#include <stdio.h>
#include <math.h>
#include <ctype.h>
#include <stdbool.h>
#include <string.h>

int main(void)
{
    float a, b, c;
    char line[100];

    printf("Enter your coordinates: ");
    while (fgets(line, sizeof(line), stdin) != NULL) {
        size_t length;

        length = strlen(line);
        if (line[length - 1] == '\n')
            line[length - 1] = 0;
        if (strcmp(line, "0,0,0") == 0)
            break;
        if (sscanf(line, "%f,%f,%f", &a, &b, &c) == 3)
            printf("\tSuccess!\n");
        else
            printf("\tTry again!\n");
        printf("Enter your coordinates: ");
    }
}

关于c++ - 在c中使用scanf停止无限while循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27987789/

相关文章:

c - GMP:初始化多个变量

c - 我不明白大小如何等于 float 而不是短整型,因为 i 的大小是短整型

c++ - 虽然循环不允许我正确解析字符串

c++ - 关于 move 一个 const 对象

c++ - C语言中delay()是什么?是系统功能吗?

c++ - 自动分配算子构造

c - 将 void 作为返回类型写入 malloc 的包装器

python - While True - 返回到层次结构的顶部

javascript - 检查所有值是否正确循环

c++ - 使用常量迭代器重载运算符