tags:

views:

180

answers:

5

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
+3  A: 

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

jonathanasdf
ah, that works. thanks a ton. also, if you dont mind, could you please explain why the .c_str() is required?
xbonez
@xbonez: Because atoi does not work on strings. It works on const char *s. atoi is a relic from the C standard. To make a string into a const char *, you call the c_str member.
Billy ONeal
C++ has 2 ways of storing strings - the first way is carried over from C, which is char*, basically an array (or pointer to an array) of chars, and the second way is the new std::string. However, they aren't equivalent and many functions expecting char*s (like the atoi function which was carried over from C) can't process std::string inputs. Thus in some cases you may need to get the C style string (c_str()) from the std::string in order to make it work.
jonathanasdf
ok, now I get it. Thanks a lot, guys.
xbonez
+1  A: 

You can do atoi(line.c_str())

Another approach, using C++ streams, is:

stringstream ss(line);
unsigned int year;
ss >> year;
Matthew Flaschen
+5  A: 

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);
Billy ONeal
+1. QFT. it's a much better way.
jonathanasdf
For error handling, when there was no number in the file, `sin.fail()` is true after the year extraction.
Rudi
+1  A: 

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.

Dan Head
+1  A: 
#include <boost/lexical_cast.hpp>

Use the lexical_cast:

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