4

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.

randominstanceOfLivingThing
  • 11,543
  • 11
  • 40
  • 66
MazzY
  • 45
  • 1
  • 1
  • 7
  • If it comes down to it, I could just go through each index of the string array and check for digits and white spaces and convert it that way, but I wonder if there is a easier and faster way like some kind of a function i could just use. – MazzY Apr 21 '16 at 02:31
  • you would typically use a function like strtok to iterate through the string and get each number in sequence – bruceg Apr 21 '16 at 02:41

3 Answers3

2

You can use a library or you can write a helper function. The helper function would look something like this (pseudocode):

int output = 0;
for (int i = 0; i < string.length; i++) {
  output = output * 10;
  output = output + parse(string[i]) //parse first character into a single digit
}

For example, if you have 253, it will read 2. Then it will multiply it by 10 (20) and add 5 (25). Then it will multiply that by 10 (250) and add 3, which will be the expected output.

Note that you need to find a way to parse a single character of your string into a single digit integer - that should be very easy using something like a switch() statement.

EDIT: If you are looking for a library function, check out this question:

What is the difference between sscanf or atoi to convert a string to an integer?

Community
  • 1
  • 1
nhouser9
  • 6,572
  • 3
  • 18
  • 39
  • gotcha, i just wrote a comment on my post few seconds after you replied that I explained the same thing as you posted. I am currently using stdio.h library that has functions like sscanf etc, I just don't know whether it can be used to convert the string to int easily, or set up a loop that goes through each element of an array and converts it. – MazzY Apr 21 '16 at 02:36
  • Got it, thank you! Link to that other post was very helpful and informative for the future. – MazzY Apr 21 '16 at 03:16
  • @MazzY No problem, happy to help. If it helped you, an upvote would be appreciated. – nhouser9 Apr 21 '16 at 03:18
  • I tried to upvote your answer and @Matthew Cliat's one, but I get this message: "Thanks for the feedback! Once you earn a total of 15 reputation, your votes will change the publicly displayed post score." Once I earn enough rep, I'll make sure to come back and upvote =). – MazzY Apr 21 '16 at 03:30
2

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!

MazzY
  • 45
  • 1
  • 1
  • 7
Matt C
  • 3,850
  • 5
  • 22
  • 42
  • 1
    Indeed it seems like I was overthinking this. I can definitely work with this code. Thank you very much. I will get back to you guys in a bit once I'm done coding – MazzY Apr 21 '16 at 02:41
  • Great! Don't forget that once the user is done entering in their numbers, they may not have filled up the array. So when you go to read or print out the numbers they gave, you'll need to stop reading/printing from the array once you have read/printed `i` elements from it. – Matt C Apr 21 '16 at 02:49
  • If i put in a negative number as the input, the loop does not stop. The negative still gets stored in an array. I am making pretty good progress on my program otherwise though – MazzY Apr 21 '16 at 03:06
  • @MazzY Oops you're right! I got a little mixed up there. You can add in another condition with && and test if num is >0. – Matt C Apr 21 '16 at 03:11
  • 2
    yeah this doesn't exit on negative input .. recommend removing that from your answer or modifying the code to make it happen. Otherwise +1. – yano Apr 21 '16 at 03:33
  • It will exit when your press `[CTRL+d]` to generate an `EOF`. (`[CTRL+z]` on windoze), or when you reach your limit of `31` integers. (now it works with edit...) – David C. Rankin Apr 21 '16 at 03:57
  • @yano MazzY was kind enough to add the code in. I'm glad to see our users are so proactive :) Both you with your suggestion, and MazzY who is a new user not only asking questions, but responding to answers even after their problem is solved. – Matt C Apr 21 '16 at 04:02
  • note: With this method you can't detect whether they press Enter at any stage – M.M Apr 21 '16 at 04:04
  • @M.M Is there a reason you would want to? – Matt C Apr 21 '16 at 04:11
  • Maybe you want the input to be terminated by pressing Enter. It seems OP was originally trying for that. – M.M Apr 21 '16 at 04:15
  • 1
    I love SO.. really I learn the most when I open my mouth thinking I know something and it turns out I actually don't. `scanf` for instance,, I don't think many people have used this beyond comp sci 101, I sure haven't anyway. I thought your answer was good until Marshall Mathers came along,, I'm not quite sure what he's getting at, I'll have to do some googling to figure it out. – yano Apr 21 '16 at 04:53
-1

It's been a while since I've worked with 'C', but here's the basic idea. To convert the char array values to integers, you'll basically have to assign each value to an int var such as:

i[0] = c[0]
i[1] = c[1]
i[2] = c[2]

The reason you can't cast the numbers directly to integer references is because C allots a contiguous memory space to hold those 3 characters. Depending on the compiler you are using will determine the char size and int size. But if the chars are 8 bits each, then an array of 3 chars is 3 bytes. 16 bit int would equal 6 bites. If you were to cast directly to ints, you wouldn't get the correct value translations because memory addresses would overlap.

user2281135
  • 43
  • 1
  • 9
  • This is simply wrong - you are right that C represents characters as integers in memory, but it does so using an ascii table. The ascii for "1" is not the same as the binary representation of the number 1. This conversion won't work. – nhouser9 Apr 21 '16 at 02:40
  • I see, thank you for the insight on the typecasting. =). How would the int array handle whitespaces if c[1] happened to be a whitespace? In my previous projects I used 30H (hexidecimal) as a reference to '0' in ASCII. In order to get digits using chars I would do something like c-'0'. – MazzY Apr 21 '16 at 02:42
  • well, if c[1] = 0x30; for example, then the following int i = c[1],....i now equals 0x30. The extra byte would just get padded with zeros. Some compilers actually store the bytes in reverse order, but that isn't really important in this example. By the way, it will also depend on whether you are using a signed char or unsigned. – user2281135 Apr 22 '16 at 09:47