Pulling one member of a string and making it an int?

后端 未结 2 506
[愿得一人]
[愿得一人] 2021-01-29 11:52

Hi I\'m trying to pull one member of a string and set that equal to an int. I understand that you can\'t simply put the int equal to the string value but I\'m not sure how else

2条回答
  •  清酒与你
    2021-01-29 12:10

    This is a common mistake. Strings are merely arrays of characters, and a (basic) character is a number between 1 and 127 (excluding some special control characters). "0" as a char is represented by the number 48, and hence "0" really equals 48, since "0" is a char and 48 is an int, and they are different ways of representing the same basic data.

    Luckily for you, there's a fairly easy way to solve your problem: Just convert each char to its equivalent int:

    cout << strzip[1] << " is equal to: " << strzip[1] - '0' << endl;
    

    Please notice that you cannot use cstdlib's atoi() function here since it will convert your whole string to a number, and in your case that will cause the loss of your leading zeroes, and probably overflow your int.

提交回复
热议问题