如何在c++中将每个特定的char转换为int



这可能是一个非常愚蠢的问题,但我已经试着去查找它,并在谷歌上搜索了一堆,但仍然找不到一个简单的方法…

在c++中,表示using namespace std;:

int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
String N;
cin >> N;
}

当用户输入123时,N"123"

如何将'1'转换为整型1,'2'转换为整型2,'3'转换为整型3?

我不能使用%.

如果我在字符串中使用索引方法,那就太棒了。

我想有一个接收N及其索引作为参数的函数。例如:

int func(string N, int curr_ind)
{
// change curr_ind of N to a single int
// for instance, "123" and 1, it would return 2.
}
#include <iostream>
#include <string>
int get_digit_from_string(const std::string&s, int idx) {
return static_cast<int>(s[idx] - '0');
}
int main() {
std::string num{"12345"};
for (std::size_t i = 0; i < num.length(); ++i) {
std::cout << get_digit_from_string(num, i) << 'n';
}
}

只获取索引处的字符,减去'0',并强制转换为int

减法是必要的,否则数字的字符将被强制转换为该字符的ASCII值。

'0'的ASCII值为48

。输出:

❯ ./a.out 
1
2
3
4
5

现在,为了好玩,假设你需要经常访问这些数字。理想情况下,您只需一次完成转换,并将这些int提供给您。这里有一种方法(需要c++ 20):

#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>
std::vector<int> get_digits_from_string(const std::string& s) {
std::vector<int> v;
std::ranges::transform(s, std::back_inserter(v),
[](auto c) { return static_cast<int>(c - '0'); });
return v;
}
int main() {
std::string num{"12345"};
std::vector<int> digits = get_digits_from_string(num);
for (auto i : digits) {
std::cout << i << 'n';
}
}

使用该字符串创建std::vector,其中每个元素都是单个字符的int。然后,我可以访问向量,轻松地得到我需要的任何数字。

另一种可能:

#include <iostream>
#include <string>
int main()
{
std::string input;
std::cin >> input;
// allocate int array for every character in input
int* value = new int[input.size()];
for (int i = 0; i < input.size(); ++i)
{
std::string t(1, input[i]);
value[i] = atoi(t.c_str());
}
// print int array
for (int i = 0; i < input.size(); ++i)
{
std::cout << value[i] << std::endl;
}
delete[] value;
}

输出:

x64/Debug/H1.exe
123
1
2
3

试试这个:

int func(string N, int curr_ind)
{
return static_cast<int>(N[curr_ind]-'0');
}

由于连续数字的ASCII表示相差1,因此将表示数字的字符(char c;)转换为相应的整数所需要做的就是:c-'0'

最新更新