Convert string to int in C++

28,045

Solution 1

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
}

Solution 2

#include <sstream>

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

Solution 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

UPDATE:

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

using namespace std;

void main()    // get rid of semicolomn 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;  
}
Share:
28,045
herohuyongtao
Author by

herohuyongtao

Stack Exchange Data Explorer - You're an amateur developer until you realize that everything you write sucks. - We're going to go that way, really fast. And if something gets in our way, we'll turn.

Updated on July 07, 2022

Comments

  • herohuyongtao
    herohuyongtao almost 2 years

    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,. any ideas? it says cannot convert std::string to const char*

    Thanks

    #include<iostream>
    
    #include<string>
    
    using namespace std;
    
    void main();
    
    {
        string s="453"
    
            int y=atoi(S);
    }
    
    • Rogue
      Rogue almost 10 years
      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
  • Admin
    Admin almost 10 years
    when i write your code this erroe apear error C2447: '{' : missing function header (old-style formal list?)
  • Mehdi Karamosly
    Mehdi Karamosly almost 10 years
    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.
  • Admin
    Admin almost 10 years
    thanks alot for your help