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
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 to share