When I run my code I get this error at compile time:
# g++ -std=c++0x sixteen.cpp -O3 -Wall -g3 -o sixteen
sixteen.cpp: In function ‘int main()’:
sixteen.cpp:10: error: call of overloaded ‘stoi(char&)’ is ambiguous
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/basic_string.h:2565: note: candidates are: int std::stoi(const std::string&, size_t*, int) <near match>
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/basic_string.h:2626: note: int std::stoi(const std::wstring&, size_t*, int) <near match>
I looked up that error and followed the instructions that other questions on here have done, however I still get that error after removing using namespace std;
. Why is this still happening and what can I do to get rid of it?
Code:
#include <iostream>
#include <string>
int main() {
std::string test = "Hello, world!";
std::string one = "123";
std::cout << "The 3rd index of the string is: " << test[3] << std::endl;
int num = std::stoi(one[2]);
printf( "The 3rd number is: %d\n", num );
return 0;
}
std::stoi
takes a std::string
as its argument, but one[2]
is a char
.
The easiest way to fix this is to use the fact that the digit characters are guaranteed to have contiguous values, so you can do:
int num = one[2] - '0';
Alternatively, you can extract the digit as a substring:
int num = std::stoi(one.substr(2,1));
And another alternative, you can construct a std::string
using the constructor that takes a char
and the number of times that char
should appear:
int num = std::stoi(std::string(1, one[2]));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With