c++ - 在数字中的特定数字处查找数字

标签 c++ c++11 numbers integer digits

<分区>

我想获取特定索引处的数字。

假设数字是“123456789”,我需要返回从左数第 3 位的数字。

我是否应该将此数字转换为字符串并将特定索引处的字符重新转换为整数以获得数字值?

在 C++ 中是否有任何内置函数可以这样做?

最佳答案

要获取数字中任意位置的数字,您可以使用简单的字符串转换:

int foo = 123456789;
int pos = 3;
// convert to string and use the [] operator
std::cout << std::to_string(foo)[pos - 1];//need to subtract 1 as C++ is 0 index based

关于c++ - 在数字中的特定数字处查找数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31613393/

相关文章:

c++ - 使用 size_t 移动 vector 索引是否安全?

c++ - 为什么#pragma optimize ("",关闭)

c++ - 在头文件中使用 lambda 会违反 ODR 吗?

c++ - std::pair 具有可比较对象和不可比较对象需要排序

末尾带零的 Javascript 舍入(固定小数位数)

C++ : How to send a struct from client to server through socket and serialize it?

c++ - AdjustWindowRect() 关闭 7 个像素?

c++ - 编译器行为和 "register storage class specifier is deprecated"

jquery输入数字

Java 字符串包含无关数据