例如,有一个字符串n,其中包含“1234”。
string n = "1234"
现在有int a,b,c,d分别存放1,2,3,4。
a is 1
b is 2
c is 3
d is 4
如何使用标准函数从字符串“12345”中获取这些数字?
以前,我是用下面的方式。
int getDigit(string fourDigitString,int order)
{
std::string myString = fourDigitString;
int fourDigitInt = atoi( myString.c_str() ); // convert string fourDigitString to int fourDigitInt
int result;
int divisor = 4 - order;
result = fourDigitInt / powerOfTen(divisor);
result = result % 10;
return result;
}
感谢您的关注
最佳答案
为了详细说明我的评论和 ShaltielQuack 的回答,所以你知道为什么你只是减去字符 '0'
从数字来看,你可能想看看 ASCII table .
在那里你会看到字符的ASCII码'0'
是十进制 48
.如果您随后看到 ASCII 代码,例如'1'
还有一个,49
.所以如果你做 '1' - '0'
这和做 49 - 48
是一样的结果是十进制值 1
.
关于c++ - 如何从字符串中获取数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19487850/