String to int

I have an integer value in a string str
I want to convert that into int and store it in a variable x.
When I am using int x=atoi(str)
It is saying cannot convert string str to const *char !
int x = atoi(str.c_str());
'Struct std::string' has no member named 'c_str'
Wow. What compiler are you using?

Do you at least have the header sstream or sstream.h?

1
2
3
4
5
6
7
8
9
10
#include <sstream> // or
// #include <sstream.h>

// ...

std::stringstream ss(str); // or
// stringstream ss(str);
int x;

ss >> x;

http://www.cplusplus.com/reference/string/string/c_str/
That's weird.
Catfish4 wrote:
What compiler are you using?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include<iostream>
#include<sstream>
using namespace std;
int main ()
{
  string s;
  stringstream ss;
  int n;
  cin>>s;
  ss<<s;
  ss>>n;
  cout<<n;
  return 0;
}
I use stringstreams too.
1
2
3
4
5
6
7
8
9
#include <string>
#include <sstream>
int strToNum(string str)
{
    istringstream ss(str);
    int n;
    ss >> n;
    return n;
}

And to convert a number to a string use:
1
2
3
4
5
6
string numToStr(int n)
{
    ostringstream ss;
    ss << n;
    return ss.str();
}
And to convert a number to a string use:
1
2
3
4
5
6
string numToStr(int n)
{
    ostringstream ss;
    ss << n;
    return ss.str();
}


That's good old, half-baked C++98 code.

1
2
3
4
5
template <typename Number>
std::string number_to_string(Number n)
{
    return dynamic_cast<std::stringstream *> (&(std::stringstream() << n))->str();
}


The proper way to do it, at least in C++11, is to use the std::to_string() functions.

http://www.cplusplus.com/reference/string/to_string/
Topic archived. No new replies allowed.