std::string to int

Why this code fails?
I am converting a string to int by indexing.

1
2
3
4
5
6
7
8
9
10
11
  #include <iostream>
  #include <string>

  int main(){

	std::string s1 = "1234567890";
	std::string s2 = s1[2]+"";
	int x = std::stoi(s2);
	std::cout<<s2;

}
im not familiar with stoi(); function but base on the error the stoi is not a member of std
why dont you look on the header file string or search in google about using it
stoi is a member of std. and it converts std::string to int. It works if i convert the whole std::string s1.
Last edited on
s1[2] is a char and "" is a const char*. There is no + operator for std::string that satisfies those parameter types. I'd wager this is the issue. Try printing s2 and see what it contains.

Something like this should work:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <string>

int main(int argc, const char** argv)
{
    std::string s1 = "1234567890";
    std::string s2 = s1[2] + std::string("");

    int x = std::stoi(s2);

    std::cout << "x is " << x << std::endl;

    return 0;
}
The problem is on line 7. You're adding a char to a pointer. The result is undefined
Line 7 doesn't do what you want. s1[2] gives you a char, which is an integer type. "" gives you a pointer.

Adding an integer n and a pointer p gives you a pointer that points to the n:th element past *p.

"" only has 1 element but s1[2] is larger than 1 so the pointer you get is out of bounds, and results in undefined behavior.

To get what you want you have to convert at least one of the two operands to a string before applying operator+.

 
std::string s2 = std::string(1, s1[2]) + "";

or

 
std::string s2 = s1[2] + std::string("");

Last edited on
Topic archived. No new replies allowed.