converting string to int in C++
I am trying to convert a string I read in from a file to an int value so 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));
Over here, setYear is a mutator in the Movie class (myMovie is an object of Movie class) that 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
Rather than using std::getline(std::string&, std::istream&)
, why not just use the stream extraction operator on the file?
ifstream sin;
sin.open("movie_output.txt");
unsigned int year = 0;
sin >> year;
myMovie.setYear(year);
myMovie.setYear(atoi(line.c_str()));
#include <boost/lexical_cast.hpp>
Use the lexical_cast:
int value = boost::lexical_cast<int>(line);
You can do atoi(line.c_str())
Another approach, using C++ streams, is:
stringstream ss(line);
unsigned int year;
ss >> year;
The quick fix is to use line.c_str() which provides a const char* for atoi().
A better solution (if available) may be to use boost::lexical_cast(line). This is a neater version of the C++ism of pushing things into and out of a std::stringstream which has all the type conversions you are likely to need.
精彩评论