質問

Let's say I have char x[3] = "123"; and I would like to convert only index 1 and index2 "23" of the char array, can I do it by atoi?

I know I can do it by char z[2]; z[0]=x[1]; z[1]=x[2]; atoi(z); but it is not what I am asking for.

役に立ちましたか?

解決

You can do this with

char x[4];
int i;

strcpy(x, "123");
i = atoi(x + 1);

Because x is a pointer to char, x + 1 is a pointer to the next char. If you try to print with

printf("%s", x + 1);

You'l get 23 as the output.

Note though that you need to declare the length of the char array to be one more than the number of characters in it - to accommodate the ending \0.

他のヒント

If you wish to convert the first digit, then the remaining part of the string, you can do:

char x[] = "123";

int first = x[0]-'0';
int rest  = atoi(&x[1]);

printf("Answers are %d and %d\n", first, rest);

Result:

Answers are 1 and 23

Yes, you can convert such a "suffix" string by giving atoi() a pointer to the first character where you want conversion to start:

const int i = atoi(x + 1);

Note that this only works for a suffix, since it will always read up to the first '\0' termiator character.

Also note, as pointed out in a question comment, that this assumes there is a terminator, which your code won't have.

You must have:

char x[4] = "123";

or just

char x[] = "123";

or

const char *x = "123";

To get the terminator to fit. If you don't have a terminated array, it's not a string, and passing a pointer to any part of it to atoi() is not valid.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top