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);
}
1
  • 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 Commented May 9, 2014 at 15:18

3 Answers 3

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
}
Sign up to request clarification or add additional context in comments.

Comments

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;
}

2 Comments

when i write your code this erroe apear error C2447: '{' : missing function header (old-style formal list?)
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.
2
#include <sstream>

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.