【问题标题】:How can I convert a character from a string into a integer variable using C++如何使用 C++ 将字符串中的字符转换为整数变量
【发布时间】:2020-02-13 00:11:54
【问题描述】:
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);

【问题讨论】:

    标签: c++ string integer character


    【解决方案1】:

    你可以试试这样的:

    #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++ 保证它只支持字符编码,其中数字具有连续且按升序排列的代码。您所拥有的可以使用 ASCII 或任何其他支持的编码。
    • 只要确保第一个char 确实在'0'..'9' 之间,然后再减去'0',否则会得到错误的结果。
    【解决方案2】:

    最简单的代码修复方法是使用 atoi 而不是 stoi 你可以像这样修改你的代码:

    string phone_nb = "173";
    char just_one_char_str[2];
    just_one_char_str[0] = phone_nb[1];
    just_one_char_str[1] = '\0';
    int i_just_one_char = atoi(just_one_char);
    

    您可以在atoi() here 上阅读更多信息

    另类

    正如@RemyLebeau 所提到的,也可以使用substr() 函数并获得类似的结果,或者也可以使用@Rietty 的答案

    string phone_nb = "173";
    string just_one_char = phone_nb.substr(0, 1);
    int i_just_one_char = stoi(just_one_char);
    

    【讨论】:

    • 您可以改用string just_one_char = phone_nb.substr(0, 1); int i_just_one_char = stoi(just_one_char);,但这只是矫枉过正。 Rietty 的回答更有效率。
    • 好吧,只要使用phone_nb.c_str() 就可以了。我不认为这是一个糟糕的解决方案
    • @ranu 将解析整个字符串,而不仅仅是第一个字符,就像 OP 想要的那样。
    • @RemyLebeau,这很容易解决。这似乎仍然不是一件坏事。
    • @ranu 要解决此问题,您必须执行 char temp[2]; temp[0] = just_one_char; temp[1] = '\0'; int i = atoi(temp); 之类的操作
    猜你喜欢
    • 2016-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-04
    • 2015-01-08
    • 1970-01-01
    • 2022-01-14
    • 2014-03-06
    相关资源
    最近更新 更多