Converting string to int in C ++

I am trying to convert a string that I read from a file to an int value so that I can store it in an integer variable. This is what my code looks like:

ifstream sin;  
sin.open("movie_output.txt");  
string line;  
getline(sin,line);  
myMovie.setYear(atoi(line));

      

Here setYear is a mutator in the Movie class (myMovie is an object of the Movie class), which looks like this:

void Movie::setYear(unsigned int year)  
{  
    year_ = year;  
}

      

When I run the code, I get the following error:

error C2664: 'atoi' : cannot convert parameter 1 from 'std::string' to 'const char *'  
1> No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called

      

+2


a source to share


5 answers


myMovie.setYear(atoi(line.c_str()));



+5


a source


Instead of using std::getline(std::string&, std::istream&)

, why not just use the stream extract operator on the file?



ifstream sin;
sin.open("movie_output.txt");
unsigned int year = 0;
sin >> year;
myMovie.setYear(year);

      

+10


a source


#include <boost/lexical_cast.hpp>

      

Use lexical_cast:

int value = boost::lexical_cast<int>(line);

      

+5


a source


You can do atoi(line.c_str())

Another approach using C ++ streams is:

stringstream ss(line);
unsigned int year;
ss >> year;

      

+3


a source


A quick fix is ​​to use line.c_str (), which provides a const char * for atoi ().

Better solution (if available) might be to use boost :: lexical_cast (string). This is a neater version of C ++ ism for pushing things in and out of std :: stringstream, which has all the type conversions you would most likely need.

+1


a source







All Articles