0

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). I.e. 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

3
  • Do you know why you took an array of pointers ? Commented Nov 14, 2012 at 1:13
  • 1
    Do you know that the addresses you're passing to sscanf() are not pointing to anything, and therefore all-but-guaranteed to seg-fault due to undefined behavior? Try int noArray[10] and pass noArray, noArray+1, noArray+2,...) etc. Commented Nov 14, 2012 at 1:15
  • Don't put a semi-colon after #include<stdio.h>. Commented Nov 14, 2012 at 5:02

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0
#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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.