c - Scanf 更多值 C

标签 c scanf

我需要有关 C 中简短代码的帮助。我必须读取输入行上用空格分隔的 float ,并且输入以 float 0 或 EOF 结束。

如果我不知道输入中有多少数字,或者它是如何工作的,并且如果我只读取数字而不是字符,则询问 EOF,该怎么做?

感谢您的回复。

一行输入示例:

12 11 10 45 50 12 EOF
12 10 11 45 0 

int main(void)  
{
    float num;
    float sum = 0;

    do{
       scanf("%f", num);
       sum += num;
    } while(EOF || num == 0);
    return 0;
}

最佳答案

来自 scanf 的手册页 -

scanf returns the number of items successfully matched and assigned which can be fewer than provided for, or even zero in the event of an early matching failure. The value EOF is returned if the end of input is reached before either the first successful conversion or a matching failure occurs.

这意味着 scanf 仅当调用时遇到 EOF 作为第一个输入时才会返回 EOF,因为 EOF 之前必须有换行符 '\n' 否则它将无法工作(取决于操作系统) 。您还必须考虑 scanf 可能遇到的匹配失败。

#include <stdio.h>

int main(void) {
    float num;
    float sum = 0;
    int val;

    while((val = scanf("%f", &num)) != EOF && val == 1) {
        sum += num;
    }

    if(val == 0) {
        printf("matching failure. input is not a float.\n");
    }
    else {
        printf("end of input.\n");
    }

    return 0;
}

关于c - Scanf 更多值 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22361004/

相关文章:

c - 如何从 C 中的 "raw"内存中读取/写入类型值?

C 程序从 .txt 文件获取每行的第一个单词并将该单词打印到另一个 .txt 文件 : Kind of works but also prints random letters

c - 如何在函数内打印指向字符数组的指针?

c - 从scanf读取不同的输入——C语言

c++ - 在这个 C++ TCP 客户端中,我在哪里设置 TCP_NODELAY?

c - 第二个 printf 不工作,需要帮​​助。 (C郎)

c - 试图让 scanf 只查看输入的前 n 个数字

c - 我修改的代码中出现未处理的异常

c - 逐行读取文本文件并从缓冲区扫描 - C

c - 二分查找不返回数组中的最后一个值