首页 > 解决方案 > Parse elements of a std::string into integers (C++)

问题描述

I am getting an odd error in my code where I try to take the elements of a std::string and convert them into 2 seperate ints

An example of the string would be "A6". I would like to be able to convert this string into 2 integers. In this example, the integers would be 65 (because 'A' is 65 in the ASCII chart) and 6.

Currently this is the code:

    // Parse string into integers
    int tempRow = userGuess[0];
    
    int tempColumn = userGuess[1];

    std::cout << tempRow << tempColumn;

"A1" outputs 65 and 49. Why does '1' become an integer of 49?

标签: c++

解决方案


The ascii code for 1 is 49, which is the result you are assigning to tempColumn. If you want the integer value, you need to do:

int tempColumn = userGuess[1] - '0';

This subtracts the ascii version of 0 which is 48 from the integer.


推荐阅读