简体   繁体   中英

Inputting array in C

Basically I have a C program where the user inputs a number (eg. 4). What that is defining is the number of integers that will go into an array (maximum of 10). However I want the user to be able to input them as "1 5 2 6" (for example). 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). 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(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. Also you shouldn't have a semicolon after your #include statement. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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