Reputation: 109
So i have a string containing numbers, and i want to take one of those numbers and convert it to an int like that :
string s = "13245";
int a = stoi(s.at(3));
I have tried stoi :
int a = stoi(s.at(3));
I have tried atoi :
int a = atoi(s.at(3));
But none of those ways works, the only way i've found is the C way :
int a = s.at(3)-'0';
Do you know why stoi / atoi don't work ? Do you have any other way to convert a character taken from a string to an int ?
Upvotes: 2
Views: 125
Reputation: 181
According to documentation:
Stoi parses str interpreting its content as an integral number of the specified base and returned an int value.
int stoi (const string& str, size_t* idx = 0, int base = 10);
Parallel to your code:
#include <iostream>
#include <string>
#include <typeinfo>
using namespace std;
string s = "13245";
cout << typeid(s.at(3)).name();
// Prints out 'c' which means 'char'
So you need to convert char to string before using stoi
#include <iostream>
#include <string>
using namespace std
string s = "13245";
string m(1,s.at(3));
int a = stoi(m);
Upvotes: 0
Reputation: 375
std::string is an array of chars and .at(3) or [3] will return you single char. stoi and atoi work on strings (many chars) and will convert string like "-42" to its number representation -42.
#include <iostream>
#include <string>
int main() {
const std::string str = "1324509";
for(const char ch: str) {
const int a = ch & 0x0f; // the same as ch - '0';
printf("%i,",a);
}
return 0;
}
Upvotes: 1
Reputation: 663
atoi accepts a const char*, whereas s.at(index) returns a char, hence the compiler will return a type error, rather you can do the following:
string s = "13245";
auto c = s.at(3);
int a = atoi(&c);
Upvotes: -2
Reputation: 311126
The function stoi
expects an object of the type std::string. The C function atoi
expects an object of the type char *
that points to a string. While you are dealing with an object of the type char.
This
int a = s.at(3)-'0';
is the common approach to convert the internal representation of a digit character to the corresponding integer value because the codes of digits follow each other without gaps.
From the C++ Standard (2.3 Character sets)
- ... In both the source and execution basic character sets, the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous.
Upvotes: 4