I have a string and i want to acces the number inside the string.
I have tried something like that,
string s="the number is 2.";
int number= stoi(s[14]);
I just want to access 2. I have used stoi but it hasn't work. what should i do?
I have a string and i want to acces the number inside the string.
I have tried something like that,
string s="the number is 2.";
int number= stoi(s[14]);
I just want to access 2. I have used stoi but it hasn't work. what should i do?
std::stoi
expects a std::string
, not a char
. If you want a single char
, you can get it out of the string like this:
int number = std::stoi(s.substr(14,1));
If you have more than 1 digit in the number you want to convert, you can just do:
int number = std::stoi(s.substr(14));
which will extract as many digits after the position as it can, to generate a number.
You can convert char
digits to its numerical value by using a simple arithmetic conversion from char
to int
:
std::string s ="the number is 2.";
int number = s[14] - '0';
You can use std::string::find_first_of()
to find the position of the first digit, then use std::string::find_first_not_of()
to find the position after the last digit, and then use std::string::substr()
to extract a sub-string containing just the digits, and then finally use std::stoi()
to convert the sub-string into an int
:
string s = "the number is 2.";
auto start = s.find_first_of("0123456789");
auto end = s.find_first_not_of("0123456789", start);
int number = stoi(s.substr(start, end-start));
Alternatively, after using std::string::find_first_of()
to find the position of the first digit, you can then pass std::string::c_str()
offset by the position to std::strtol()
:
string s = "the number is 2.";
auto start = s.find_first_of("0123456789");
int number = std::strtol(str.c_str() + start, nullptr, 10);
For a conversion logic that doesn't assume a single digit number, here's a slightly more universal snippet:
string s="the number is 234.";
int number= atoi(s.c_str() + 14);