gpt4 book ai didi

c++ - 如何使用C++将字符从字符串转换为整数变量

转载 作者:行者123 更新时间:2023-12-02 09:50:21 26 4
gpt4 key购买 nike

string phone_nb = "173";
char just_one_char = phone_nb[1];
int i_just_one_char = stoi(just_one_char);

我得到这些错误:
no matching function for call to 'stoi'
int i_just_one_char = stoi(just_one_char);

note: candidate function not viable: no known conversion from 'char' to 'const std::__1::string' (aka 'const basic_string<char, char_traits<char>, allocator<char> >') for 1st argument
_LIBCPP_FUNC_VIS int stoi (const string& __str, size_t* __idx = 0, int __base = 10);

note: candidate function not viable: no known conversion from 'char' to 'const std::__1::wstring' (aka 'const basic_string<wchar_t, char_traits<wchar_t>, allocator<wchar_t> >') for 1st argument
_LIBCPP_FUNC_VIS int stoi (const wstring& __str, size_t* __idx = 0, int __base = 10);

最佳答案

您可以尝试如下操作:

#include <iostream>
#include <string>

int main() {
std::string phone_nb = "173";
int i_just_one_char = phone_nb[0] - '0';
std::cout << i_just_one_char;
}

通过依靠字符/ ASCII的结构将字符转换为等效的整数来工作。

上面的代码将输出一个 1

关于c++ - 如何使用C++将字符从字符串转换为整数变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60198728/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com