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

后端 未结 2 507
[愿得一人]
[愿得一人] 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.

    0 讨论(0)
  • 2021-01-29 12:22

    Each element in a string is castable to an int implicitly (a basic_string contains char type items which are mapped to ascii characters in standard in/out methods.) Since each character is a number from 0 to 255 mapping to this table you can see how this plays out:

    if('0' == 48){cout << "0 char is 48 int";}
    

    C++ has several conversion methods. With simple char types you can exploit the basic ascii table layout and treat it as a number:

    int resultNumber = mystring[i] - '0';
    

    Using the above method, you would be wise to check the character is in the range of '0' to '9' first. The following does that check and returns -1 in the case of an error.

    int resultNumber = (mystring[i] >= '0' && mystring[i] <= '9')?mystring[i] - '0':-1;
    

    But you can also use stoi because char will implicitly convert to a string. This has the distinct benefit of working for more than a simple char. There is minor overhead for casting a single character to a string vs the previous method, however.

    int resultNumber = stoi(mystring[i]);
    

    You can cast a whole string at once if you want (this will not work in your case because you want to check each character individually, but for a 2+ digit number it will work.)

    C's atoi does the same thing but requires a char* (C style string) which will not implicitly work with a char type (casting to char* with &mystring[i] would also not work because it requires null termination).

    0 讨论(0)
提交回复
热议问题