Ambitious
Ambitious

Reputation: 55

Convert char String to an int but not possible to convert a char from an char string to an int?

char input[5] = "12345";

printf("Convert to int valid %d", atoi(input));
printf("Convert to int invalid %d", atoi(input[1])); // program crash

Is there a solution to convert an char "slice" of an char string into an int? Short description:

User inputs a string with values for example: 1, 2 3 4 ,5 Iam formating that string to 12345 With each number i want to continue to work with the index of an array.

Upvotes: 2

Views: 204

Answers (2)

Mad Physicist
Mad Physicist

Reputation: 114578

To properly convert an arbitrary slice, you have to either make a copy or modify the string by inserting a \0 after the slice. The latter may not be an option, depending on where the string is stored.

To make a copy, allocate an array big enough to hold the slice and a \0. If you know the size of the slice at compile time, you can allocate on the stack:

char slice[2];

Otherwise, you'll have to allocate dynamically:

char *slice;

slice = malloc(2);

Stack allocated slices do not need to be deallocated, but dynamically allocated ones should be freed as soon as they are no longer needed:

free(slice);

Once you have the slice allocated, copy the portion of interest and terminate it with \0:

strncpy(slice, s + 1, 1);
slice[1] = '\0';
atoi(slice);

This technique will pretty much always work.

If your slice always ends with the string, you don't need to make a copy: you just need to pass a pointer to the start of the slice:

atoi(s + 1);

Modifying the string itself probably won't work, unless it's in writeable memory. If you're sure this is the case, you can do something like:

char tmp;

tmp = s[1];
s[1] = '\0';
atoi(s);
s[1] = tmp;

If you were sure but the memory wasn't writeable, your program will seg-fault.

For the special case where your slice is exactly one character long, you can use the fact that characters are numbers:

s[0] - '0'

Note that '0' !='\0' and that this won't work if your machine uses EBCDIC or similar.

Upvotes: 2

Govind Parmar
Govind Parmar

Reputation: 21572

If you mean "how to access a substring in the char [] array", you can use pointer arithmetic:

char input[6] = "12345";
printf("strtol(input + 1) = %d\n", strtol(input + 1, NULL, 10)); // Output = "2345";

Few things to note though:

  1. Your array should be 6 elements long to hold the null terminator
  2. atoi shouldn't be used at all; strtol is a better function for the task of converting a string to a signed integer; see here for more info.

Also, to convert a single character to an int:

if(isdigit(c))
{
     c -= '0';
}

The relation that a textual representation of a digit is exactly '0' higher than the numeric value of that digit is guaranteed to hold for every character set supported by C.

Upvotes: 4

Related Questions