0

I have a string, xxxxxxxxxxxxxxxxxxx

I am reading the string into a structure of smaller strings, and using substr to parse it. I need to convert one of those string types to integer.

atoi is not working for me. How can I do it? It says:

cannot convert std::string to const char*

Code

#include <iostream>
#include <string>

using namespace std;

void main();
{
    string s = "453"

    int y = atoi(S);
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user3472947
  • 49
  • 1
  • 1
  • 2
  • `atoi` is not a very good function to use if you need to validate that it successfully converted, something better to use would be `strtol`: [Documentation](http://www.cplusplus.com/reference/cstdlib/strtol/) – Rogue May 09 '14 at 15:18

3 Answers3

6

std::atoi() requires const char * to pass in.

Change it to:

int y = atoi(s.c_str());

or use std::stoi() which you can pass a string directly:

int y = stoi(s);

You program has several other errors. Workable code could be something like:

#include<iostream>
#include<string>
using namespace std;

int main()
{
    string s = "453";
    int y = atoi(s.c_str());
    // int y = stoi(s); // another method
}
herohuyongtao
  • 49,413
  • 29
  • 133
  • 174
3

In C++, the case matters. If you declare your string as s, you need to use s, not S when calling it. You are also missing a semicolon to mark the end of the instruction. On top of that, the atoi takes char * as parameter not a string, so you need to pass in an array of char or a pointer to a char array:

Function signature: int atoi (const char * str);

string s = "453"; // Missing ';'

int y = atoi(s.c_str());  // Need to use s, not S

Full code:

#include <cstdlib>
#include <iostream>
#include <string>

using namespace std;

void main()    // Get rid of the semicolon here
{
    string s = "453"; // Missing ';'
    int y = atoi(s.c_str());  // Need to use s, not S
    cout << "y =\n";
    cout << y;
    char e;     // This and the below line is just to hold the
                // program and avoid the window/program to
                // close until you press one key.
    cin  >> e;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mehdi Karamosly
  • 5,388
  • 2
  • 32
  • 50
  • when i write your code this erroe apear error C2447: '{' : missing function header (old-style formal list?) – user3472947 May 09 '14 at 16:33
  • you need to include whatever header your atoi function belongs to, and you need to make sure you include header of any function you us. take a look at the updated code. – Mehdi Karamosly May 09 '14 at 16:40
2
#include <sstream>

int toInt(std::string str)
{
    int num;
    std::stringstream ss(str);
    ss >> num;
    return num;
}