anshdeb
anshdeb

Reputation: 1

How to fill an array without hitting enter in a for loop

I know this might seem a very noob question, but I am very confused at the moment. Is there any way to accept values from the user into an array without hitting enter every time ?

Like if the number of values to accept is 3, so the user can enter values as 5 25 45 and hit enter and it gets stored in the array as three separate values.

I am trying to do this with a for loop but it only accepts the next value once I hit enter.

Upvotes: 0

Views: 1480

Answers (3)

TZer0
TZer0

Reputation: 53

Use strtok!

Please remember to include string.h.

CharArrayToMatch will in this case be the input string from the user. Let's for sake of example say that it is "1 2 3 4 5".

{1} will get the first number - 1 and make strtok "ready" for the read the rest of the string.

{2} prints the current token - replace this with whatever you want to do.

{3} as long as this does not return NULL, there are more tokens to process.

When we enter the loop, we will first print 1, then get the next number: 2, put it into tmp, then repeat the process with the other numbers. After 5, strtok will return NULL and we'll exit the loop.

 // We split on spaces and get the pointer to the first token    
char *tmp = strtok(CharArrayToMatch, " "); // {1}

while (tmp != NULL) {
    // do whatever action you want to do instead of this - for instance: atoi!
    printf("%s\n", tmp); // {2}
    // Get the next token
    tmp = strtok(NULL, " "); // {3}
}

Edit #1: added a few comments.

Edit #2: Please note that this solution actually handles a generic number of inputs.

Edit #3: quick attempt at making it clearer.

Upvotes: 1

Jasper
Jasper

Reputation: 300

You have to save that line as a string, then parse it (split it up) with a different function. You should be able to look up how to do that. Try googling "parse string c" or something along those lines.

EDIT: pmg's solution is much simpler, and works for your purposes. I'd use that.

Upvotes: 1

pmg
pmg

Reputation: 108988

This works

#include <stdio.h>

int main(void) {
    int array[10];
    printf("Enter 10 values separated by whitespace (enter, space, tab, ...)\n");
    for (int k = 0; k < 10; k++) {
        if (scanf("%d", array + k) != 1) /* error */;
    }
    return 0;
}

Upvotes: 6

Related Questions