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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With