user209306
user209306

Reputation: 89

Getting multiple ints from user as input

I know C++ but I am trying to write my first C program and I'd like to be able to get one line of input from a user and convert it to 10 different numbers. For example, a user will be prompted to enter some numbers and they will enter up to 10 numbers:

Input up to 10 numbers:

> 34412 12455 435234 44 199 4735890 034001 154595

Then I'd like to store them an in array and do stuff with them later. I've searched for how to get input but most of what I've found isn't clear to me. Any help would be appreciated, thanks!

Upvotes: 2

Views: 4464

Answers (3)

Ayberk
Ayberk

Reputation: 410

If you are sure that the user is always going enter integers separated by spaces/tabs and newlines, and not more than 10 of them, you can use this one liner to do the trick:

int arr[10];
int count = 0;

while(scanf("%d",&(arr[count++])))
   ;

It takes advantage of the fact that scanf returns number of items matched.

Upvotes: 2

LihO
LihO

Reputation: 42103

You can read line from users input, tokenize it and then directly retrieve numbers from tokens by using sscanf:

// array big enough to hold 10 numbers:
int numbers[10] = {0};

// read line from users input:
char inputString[200];
fgets(inputString, 200, stdin);

// split input string into tokens:
char *token = strtok(inputString, " ");

// retrieve a number from each token:
int i = 0;
while (token != NULL && i < 10) {
    if (sscanf(token, "%d", &numbers[i++]) != 1)
        ; // TODO: ERROR: number hasn't been retrieved
    token = strtok(NULL, " ");
}

Upvotes: 1

P.P
P.P

Reputation: 121407

You have a bit of reading to do about few C functions:

  1. fgets() to read a whole line. Remove the newline at the end.
  2. strtok() to tokenize the line.
  3. strtol() to convert each string into an integer.
  4. Store them in an array.

If you are not worried about invalid inputs, you can use sscanf() to read from C-string.

Upvotes: 1

Related Questions