在C++中如何将字符串转换为整数?

在C++中如何将字符串转换为整数?,c++,C++,我想把C++中的字符串转换成int,下面的代码是打印两个数字的和的最后一个数字。我知道我可以用其他不同的方法来做,但我很好奇为什么下面的代码会显示错误 代码: 错误: prog.cpp: In function 'int main()': prog.cpp:12:40: error: invalid conversion from '__gnu_cxx::__alloc_traits<std::allocator<char> >::value_type {aka cha

我想把C++中的字符串转换成int,下面的代码是打印两个数字的和的最后一个数字。我知道我可以用其他不同的方法来做,但我很好奇为什么下面的代码会显示错误

代码:

错误:


prog.cpp: In function 'int main()':
prog.cpp:12:40: error: invalid conversion from '__gnu_cxx::__alloc_traits<std::allocator<char> >::value_type {aka char}' to 'const char*' [-fpermissive]
         cout<< atoi(ans[ans.length()-1])<<endl;
                                        ^
In file included from /usr/include/c++/5/cstdlib:72:0,
                 from /usr/include/x86_64-linux-gnu/c++/5/bits/stdc++.h:47,
                 from prog.cpp:2:
/usr/include/stdlib.h:147:12: note:   initializing argument 1 of 'int atoi(const char*)'
 extern int atoi (const char *__nptr)
我已经使用了STOI和ATOI,但是我仍然显示这个错误

您能告诉我为什么会产生此错误以及如何解决它吗。

来自

函数atoi需要一个常量char*

ans[ans.length()-1]
这将检索std::string ans的最后一个元素,即char。您将得到一个错误,因为您正在向需要常量char*的函数提供一个char。您可以打印出最后一位数字,而无需转换:

cout<< ans[ans.length()-1] <<endl;

您已经可以找到对此的现有解释:

Atoi仅在param中接收常量字符。您可以改用stoi:

cout<< stoi(ans)%10<<endl;
您可以使用库sstreamas的stringstream类,如下所示:

string s = "23031"; 

    stringstream test(s);
    int x = 0; 
    test>> x; 

    // Now the variable x holds the value 23031
    cout << "Value of x : " << x; 

在上面的代码中,x有一个整数值

atoi接受一个常量字符*,而不是一个字符。为什么不这样做呢:std::cout您不需要将最后一个数字转换成一个数字来打印它。您不需要将数字转换为字符串来提取其最后一个数字,只需删除对atoi的调用并直接显示所需的字符:std::cout@AyushPant查看我的答案。老实说,我认为这里不太需要使用stoi或atoi;毕竟,您只想将一个字符转换为int。
int last_digit = ans[ans.length()-1] - '0';
cout<< stoi(ans)%10<<endl;
string s = "23031"; 

    stringstream test(s);
    int x = 0; 
    test>> x; 

    // Now the variable x holds the value 23031
    cout << "Value of x : " << x;