tariq
tariq

Reputation: 529

get last integer value from char array

Consider a char array like this:

43 234 32 32

I want the last value that is 32 in integer form.

The string size/length is not known. In the above example there are 4 numbers, but the size will vary.

How can this be done?

Upvotes: 0

Views: 3035

Answers (5)

JRK
JRK

Reputation: 182

I guess you want to use a combination of strtok_r and atoi

Upvotes: 0

archbishop
archbishop

Reputation: 1127

If there is no trailing whitespace on the line:

int last_int(const char *s)
{
    const char *ptr = strrchr(s, ' ');
    if (ptr == NULL) {
        ptr = s;
    } else {
        ptr++;
    }

    return atoi(ptr);
}

If there can be trailing whitespace, then you'll need to do something like what ProdigySim suggested, but with more states, to walk backwards past the trailing whitespace (if any), then past the number, then call atoi(). No matter what you do, you'll need to watch out for boundary conditions and edge cases and decide how you want to handle them.

Upvotes: 0

ProdigySim
ProdigySim

Reputation: 2933

int getLastInt(char *data)
{
    size_t i = strlen(data);
    if(!i--) return -1; // failure
    for(;i;--i)
    {
        if(data[i] == ' ')
        {
            return atoi(&data[i+1]);
        }
    }
    return -1; // failure
}

Should work as long as the data has a space + actual text. You could also skip the strlen and just loop forward, which could be faster depending on your system's strlen.

Upvotes: 1

Murali VP
Murali VP

Reputation: 6417

i have copied these value from the file onto char array.now i want the last number in integer variable

When you were copying,add a counter of # of characters copied. Then do this

int count = 0;
char c;
while(c = readCharFromFile()) {
  array[count++] = c;
}

int last = array[count - 1];

Upvotes: 3

dex black
dex black

Reputation: 647

There are many ways to solve this.

  1. Convert every token (space delimited string) into a number and when the tokens run out return the last value converted.

  2. Scan the line for tokens until you get to the end and then convert the last token into a number.

  3. Start at the end of the line. Skip spaces and store digits until the first space is encountered and then convert the result to a number.

  4. Split the string into an array of strings and convert the last one into a number.

I could go on and on but you get the idea I hope.

Upvotes: 2

Related Questions