c++ - 如何从字符串中获取数字?

标签 c++ digit

例如,有一个字符串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/

相关文章:

java - 在 C++ 和 Java 之间传输数据最快的方法是什么

c++ - 为什么运行时堆栈对象的实例变量与堆对象不同?

c# - 在 C#/.NET 的其他语言环境中格式化数字和日期

c - 在C中逐位递归地求和两个数字

c++ - 优先级特化

我的类中的 C++ 运行时错误

c++ - 注入(inject)的 DLL 主循环导致进程崩溃

c++ - 回文整数检查器

java - 强制 JTextField 为字符串值,而 DocumentFilter 只允许数字

c - C-如何检查数字出现在数字中的次数