c++ - 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?
解决方案
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.
推荐阅读
- c++ - 我用 Gstreamer MSVC 1.16.1 构建 opencv 3.4,现在 imread 和 VideoCapture 不起作用
- regex - 如何通过删除postgres中的中间部分来获取字符串
- python-3.x - 循环中打印位置导致的差异
- scala - Spark Scala 中的点积
- mysql - 如何在mysql中找到平均差异?
- sql - 如果我的要求是 postgresql 和 sql server,如何使 spring boot 代码通用或动态?
- c# - Lamda 表达式不适用于 String.Count()
- python - 在矩形matplotlib内绘制线宽
- git - 如何在 Google Colab 中的 GitHub 分支之间切换
- azure - 如何将与 VNet 集成的 azure 函数应用程序列入 Even Grid 订阅白名单