如何用更少的参数停止 scanf

发布于 2025-01-13 05:47:06 字数 445 浏览 5 评论 0原文

我需要不断从键盘获取 3 个值(int、int、float),并且只有在输入 0 时才停止循环。

问题是,当我输入 0 并按 [Enter 时,它会一直等待第二个和第三个值。

    int i, j; float v;
    while (scanf("%i %i %f", &i, &j, &v) == 3){
        Matrix* M = (Matrix*)malloc(sizeof(Matrix));
        M->line = i;
        M->column = j;
        M->info = v;
        printf("loop");
    }

我知道 scanf 返回一个整数,表示成功捕获的值的数量,问题是:如何停止等待新输入并返回已捕获的数量。 (所以在这种情况下我可以退出循环。)

I need to keep getting 3 values ​​(int, int, float) from the keyboard and only stop the loop when I enter 0.

The problem is that when I enter 0 and press [Enter it keeps waiting for the second and third value.

    int i, j; float v;
    while (scanf("%i %i %f", &i, &j, &v) == 3){
        Matrix* M = (Matrix*)malloc(sizeof(Matrix));
        M->line = i;
        M->column = j;
        M->info = v;
        printf("loop");
    }

I know that scanf returns an integer representing the number of successfully captured values, the question is: How to stop waiting for new inputs and return the number of already captured. (So i can exit the loop in this case.)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浅唱々樱花落 2025-01-20 05:47:07

我会考虑只读取循环中的整行,然后在循环内使用 sscanf 解析该行。返回值 1 和解析为 0 的第一个值将指示您想要的结束条件。当您拥有完整的产品线时,您还可以提供更好的错误诊断。

I would consider just reading whole lines in the loop and then parsing that line using sscanf inside the loop. Return value 1 and the first value parsed as 0 would indicate your desired ending condition. When you had the complete line available, you could also present better error diagnostics.

瑕疵 2025-01-20 05:47:07

正如其他人所建议的,您可以尝试一下:

    char line[BUFSIZ];

    while (fgets(line, BUFSIZ, stdin)) {
        if (strcmp(line, "0\n") == 0 || strcmp(line, "q\n") == 0)
            break;
        else {
            sscanf(line, "%i %i %f", &i, &j, &v);
            ...
        }
    }

仅输入 0q 将退出循环。

As suggested by others, would you please try:

    char line[BUFSIZ];

    while (fgets(line, BUFSIZ, stdin)) {
        if (strcmp(line, "0\n") == 0 || strcmp(line, "q\n") == 0)
            break;
        else {
            sscanf(line, "%i %i %f", &i, &j, &v);
            ...
        }
    }

Entering just 0 or q will exit the loop.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文