C、从一次 scanf 中读取多个数字

标签 c arrays console scanf

我有一项作业,要求我执行一次 scanf 并对多个整数执行一些数学运算。输入中的第一个数字设置后面的整数数量,即:3 45 67 18 应解释为 N var1 var2 var3,4 100 23 76 92 应解释为 N var1 var2 var3 var4。我无法按照第一次迭代的指示编写程序,但它确实按预期工作。我通过简单地将 scanf 放入运行 N 次的循环中并将剩余数字存储在数组 n[1000] 中来完成存储 var1 var2... varN 。就像我说的,该程序可以工作......有点,但它不按照作业指示的方式工作。作业提供的示例运行应该是:

Please enter n followed by n numbers: 3 6 12 17

Test case #1: 6 is NOT abundant.
Test case #2: 12 is abundant.
Test case #3: 17 is NOT abundant.

我的程序输出是:

Please enter n followed by n numbers: 3
6
12
17
Test case #1: 6 is NOT abundant.
Test case #2: 12 is abundant.
Test case #3: 17 is NOT abundant.

这是link到我的程序。 我已经阅读了许多类似的问题,但大多数似乎都轻视了 scanf 的使用,而不是从控制台捕获输入的其他方法。 This post与我正在寻找的答案非常接近,只是我需要动态设置数量的变量。我有一种感觉,我需要使用 malloc 函数,但我不太确定如何使用它来实现这一点,并且仍然完成单行 scanf 输入。

谢谢

最佳答案

好吧,我测试了它,你确实可以使用 scanf 来做到这一点。

#include<stdio.h>

int main(){
    int total = 0;
    int args;
    char newline;
    do{
        int temp; 
        args = scanf( "%d%c", &temp, &newline );
        if( args > 0 )
            total += temp;
        puts( "Internal loop print test");
    } while( newline != '\n' );
    printf( "\n\n%d", total );
    return 0;
}

控制台日志:

1 2 3 9
Internal loop print test
Internal loop print test
Internal loop print test
Internal loop print test


15

编辑:由于几个已知的漏洞问题,我从未使用过 scanf 系列,但我什至没有想到尝试使用 scanf。我以为它会读到换行符,但它与 scanf 一起工作得很好。 Aniket 的评论让我想尝试一下。

关于C、从一次 scanf 中读取多个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14759434/

相关文章:

c - 编译器在赋值操作期间如何工作?

c - 使用 stdio 写入文件

php - PDO 检索二维数组而不是一维数组

java - 返回 Null 值的数组

c# - 该名称门在当前上下文中不存在

没有控制台的 C++ popen 命令

澄清并记住 C 中的 const 用法

linux - 如何从用户空间 C 代码中获取 Linux 内核模块列表?

php - 将数组存储在字符串中并稍后传递给 eval()

playframework - Play -“在/0:0:0:0:0:0:0:0:0%0:9000上收听HTTP”