如何从字符串中获取数字
How to get a digit from a string?
例如,有一个包含"1234"的字符串n。
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表。
在那里,您将看到字符'0'
的 ASCII 代码是十进制48
。如果您随后看到 ASCII 代码,例如 '1'
又是一个,49
.因此,如果您执行'1' - '0'
则与执行49 - 48
相同,这会导致十进制值1
。
std::string n ("12345");
int a, b, c, d, e;
a = str.at(0);
...
#include <iostream>
using namespace std;
int main() {
string n = "12345";
int a = n[0] - '0';
int b = n[1] - '0';
int c = n[2] - '0';
int d = n[3] - '0';
int e = n[4] - '0';
cout << a << endl;
cout << b << endl;
cout << c << endl;
cout << d << endl;
cout << e << endl;
}
输出:
1阿拉伯数字
3
四
5
您可以尝试以下代码:
#include <string>
#include <sstream>
int main() {
std::string s = "100 123 42";
std::istringstream is( s );
int n;
while( is >> n ) {
// do something with n
}
}
从这个问题:从字符串中拆分 int
相关文章:
- QChar 如果 'isDigit()' 则获取数字值
- 从(排序的)数字列表中获取数字范围
- 如何以正确的时区从XTS索引中获取数字时间?
- 如何获取数字的更改
- 如何仅从字符串中获取数字
- 获取数字小数部分的最佳方法
- 获取数字最左边两个位的值的最便宜的方法是什么?
- 从.txt文件中获取数字,并将其放入C 中的向量
- 如何从文件中获取数字行并忽略第一个数字
- 无法从字符串获取数字输入
- 欧拉项目 #3 获取数字的最大质因数
- 从 JNI 中的原语获取数字的简单方法
- 如何按位获取数字而不是求反符号位
- C 如何在文件中的特定字符串之后获取数字
- 获取数字序列的功能
- 使用sscanf c++检查格式并获取数字
- 如何从 9 和 90 中提取 2.9 和 2.09,即获取数字等于最大编号的小数部分.二分位数之后的数字
- 如何从班级中获取数字?C++
- 如何从字符串中获取数字
- 从用户输入中获取数字,直到用户类型"quit"