简体   繁体   English

如何在C的一行中获得多个输入?

[英]How to get multiple inputs in one line in C?

I know that I can use 我知道我可以用

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

But what if the user first determines how many input there'd be in the line? 但是,如果用户首先确定该行中会有多少输入,该怎么办?

You are reading the number of inputs and then repeatedly (in a loop) read each input, eg: 您正在读取输入的数量,然后反复(循环)读取每个输入,例如:

#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);
}

Read in the whole line, then use a loop to parse out what you need. 阅读整行内容,然后使用循环解析您需要的内容。

To get you started: 为了帮助您入门:

1) Here is the manual page for getline(3): http://man7.org/linux/man-pages/man3/getline.3.html 1)这是getline(3)的手册页: http : //man7.org/linux/man-pages/man3/getline.3.html

2) Some alternatves to getline: How to read a line from the console in C? 2)一些替代方法: 如何从C语言的控制台中读取一行?

3) Consider compressing spaces: How do I replace multiple spaces with a single space? 3)考虑压缩空间: 如何用单个空间替换多个空间?

4) Use a loop for parsing. 4)使用循环进行解析。 You might consider tokenizing: Tokenizing strings in C 您可能会考虑标记化: 在C语言中标记字符串

5) Be careful and remember that your user could enter anything. 5)注意并记住您的用户可以输入任何内容。

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

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