【问题标题】:How to get multiple inputs in one line in C?如何在C中的一行中获取多个输入?
【发布时间】:2014-06-24 22:15:40
【问题描述】:

我知道我可以使用

scanf("%d %d %d",&a,&b,&c): 

但是如果用户首先确定一行中有多少输入呢?

【问题讨论】:

  • 只使用一个循环。

标签: c input scanf


【解决方案1】:

您正在读取输入的数量,然后重复(循环)读取每个输入,例如:

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

int main(int ac, char **av)
{
        int numInputs;
        int *input;

        printf("Total number of inputs: ");
        scanf("%d", &numInputs);

        input = malloc(numInputs * sizeof(int));

        for (int i=0; i < numInputs; i++)
        {
                printf("Input #%d: ", i+1);
                scanf("%d", &input[i]);
        }

        // Do Stuff, for example print them:
        for (int i=0; i < numInputs; i++)
        {
                printf("Input #%d = %d\n", i+1, input[i]);
        }

        free(input);
}

【讨论】:

  • 如果我删除 printf("Input #");代码还能按要求工作吗?
【解决方案2】:

读入整行,然后使用循环解析出你需要的内容。

让您开始:

1) 这是 getline(3) 的手册页: http://man7.org/linux/man-pages/man3/getline.3.html

2) getline 的一些替代方案: How to read a line from the console in C?

3) 考虑压缩空格: How do I replace multiple spaces with a single space?

4) 使用循环进行解析。您可能会考虑标记化: Tokenizing strings in C

5) 请注意,您的用户可以输入任何内容。

【讨论】:

    【解决方案3】:
    #include <conio.h>
    #include <stdio.h>
    main()
    {
        int  a[100],i,n_input,inputs;
        printf("Enter the number of inputs");
        scanf("%d",&n_input);
    
        for(i=0;i<n_input;i++)
        {
            printf("Input #%d: ",i+1);
            scanf("%d",&a[i]);
        }
    
        for(i=0;i<n_input;i++)
        {
            printf("\nInput #%d: %d ",i+1,a[i]);
        
        }
    
    }    
    

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 2014-06-02
    • 2022-01-10
    • 1970-01-01
    • 2022-10-23
    • 1970-01-01
    相关资源
    最近更新 更多