繁体   English   中英

C,从单个scanf读取多个数字

[英]C, reading multiple numbers from a single 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.

这是我的程序的链接 我已经阅读了许多类似的问题,但大多数似乎都忽视了scanf的使用,而不是从控制台捕获输入的其他方法。 这篇文章非常接近我正在寻找的答案,除了我需要动态设定数量的变量。 我有一种感觉,我需要使用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的评论让我想尝试一下。

以下代码对我有用:

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


int main(void)
{
    int n[1000],i,j,sum,size;

    printf("Please enter n followed by n numbers: ");
    scanf("%d",&n[0]);

    for (i=1;i<=n[0];i++)
            scanf("%d",&n[i]);

        /* Debug: Automatically generate numbers from 1 to n[0] */
        //n[i]=i

    for (i=1;i<=n[0];i++)
    {
        /* Debug: See what numbers are being used in sum - Part 1*/
        //printf("\nFactors < %d of %d: ",n[i]/2,n[i]);
        sum=0;
        for (j=1;j<=n[i]/2;j++)
        {

            if (n[i]%j==0)
            {
                /* Debug: See what numbers are being used in sum - Part 2*/
                //printf("%d ",j);
                sum+=j;
            }

        }
        printf("Test case #%d: %d is%sabundant.\n",i,n[i],(sum>n[i])?" ":" NOT ");

        /* Debug: See what numbers are being used in sum - Part 3*/
        //printf("(%d)\n",sum);
    }
    system("PAUSE");    
    return 0;
}

Aslai你的回答让我感到困惑,因为我无法看到你的代码将如何完成与我所做的不同。 因此,当我调试以查看返回的scanf时,我注意到scanf实际上在每个空格后返回,而不是像我想的那样“输入”或“\\ n”。 所以我简化了我的第一个for循环,一切正常。 我是否正确地说,只要有足够的后续scanf调用,来自一个scanf的输入将满足后续scanf的变量赋值? 换句话说,如果我在单次扫描期间输入3 25 17,那么我可以将这些数字中的每一个分配给变量以及后续的scanf调用而无需按Enter键吗?

scanf("%d",&var1); //(where var1=3)
scanf("%d",&var2); //(where var2=25) 
scanf("%d",&var3); //(where var3=17)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM