简体   繁体   English

在C中输入数组

[英]Inputting array in C

Basically I have a C program where the user inputs a number (eg. 4). 基本上我有一个C程序,用户在其中输入数字(例如4)。 What that is defining is the number of integers that will go into an array (maximum of 10). 定义的是将进入数组的整数数量(最大为10)。 However I want the user to be able to input them as "1 5 2 6" (for example). 但是我希望用户能够将它们输入为“ 1 5 2 6”(例如)。 Ie as a white space delimited list. 即作为空格分隔的列表。

So far: 至今:

#include<stdio.h>;

int main()
{
    int no, *noArray[10];    
    printf("Enter no. of variables for array");
    scanf("%d", &no);

    printf("Enter the %d values of the array", no);
    //this is where I want the scanf to be generated automatically. eg:
    scanf("%d %d %d %d", noArray[0], noArray[1], noArray[2], noArray[3]);

    return 0; 
}

Not sure how I might do this? 不知道我该怎么做?

Thanks 谢谢

scanf automatically consumes any whitespace that comes before the format specifier/percentage sign (except in the case of %c, which consumes one character at a time, including whitespace). scanf自动消耗格式说明符/百分号之前的所有空白(%c除外,它一次消耗一个字符,包括空白)。 This means that a line like: 这意味着一行如下:

scanf("%d", &no);

actually reads and ignores all the whitespace before the integer you want to read. 实际读取并忽略您要读取的整数之前的所有空格。 So you can easily read an arbitrary number of integers separated by whitespace using a for loop: 因此,您可以使用for循环轻松读取由空格分隔的任意整数:

for(int i = 0; i < no; i++) {
  scanf("%d", &noArray[i]);
}

Note that noArray should be an array of ints and you need to pass the address of each element to scanf, as mentioned above. 请注意,如上所述,noArray应该是一个整数数组,您需要将每个元素的地址传递给scanf。 Also you shouldn't have a semicolon after your #include statement. 另外,您在#include语句后不应使用分号。 The compiler should give you a warning if not an error for that. 编译器应该给您警告,如果不是错误的话。

#include <stdio.h>

int main(int argc,char *argv[])
{
    int no,noArray[10];
    int i = 0;

    scanf("%d",&no);
    while(no > 10)
    {
        printf("The no must be smaller than 10,please input again\n");
        scanf("%d",&no);
    }
    for(i = 0;i < no;i++)
    {
        scanf("%d",&noArray[i]);
    }
    return 0;
}

You can try it like this. 您可以这样尝试。

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

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