C Converting Char array (strings) into int array

MazzY

I have been searching around for hours for this, but I can't seem to find an answer, especially when it comes to C language. In java it would be simple matter of casting and such, but I just cant seem to get a firm grip on it in C.

My problem is: I have to get an input from a user, they can enter any number from 0 to 31. They can enter up to 31 numbers. They can repeat. The input could look like this: 3 15 32. I know how to take this input and store it as a string using the fgets() function. I store the input in array s[];

Now, the part that I am stuck on, how do I convert that to an int array so that int int[0]=3, i[1]=15, i[2]=32, etc.

I tried using sscanf(s, "%d", int), but it only is able to get the first number from the input, stores it in int[0], and then doesn't fill in the rest. Is there some kind of a function that makes this all easy and quick?

Thank you in advance.

Matt C

You might be overthinking things. Here's a simply way to input numbers from a user that doesn't involve formatting or parsing strings.

int numArray[31];
int i = 0;
int num = 0;

while( scanf("%d", &num) > 0 && i < 31 && num >0) {
    numArray[i] = num;
    i++;
}

The loop will stop when the user enters a negative number, or has entered all 31 possible numbers.

You still have to make sure the user enters a number between 0 and 31 though!

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

TOP Ranking

HotTag

Archive