As
Shilpi Boosar already said, the input string must be a valid integer, otherwise the result will be 0.
If all you want is to accept only integers as input you can use this:
int intReturn;
if(std::cin >> intReturn)
{
std::cout << intReturn;
}
For a conversion from
string
to
int
you can also use (as an alternative to
atoi
):
std::string str = "567";
std::istringstream iss(str);
int intReturn;
if(iss >> intReturn)
{
std::cout << intReturn;
}
Using
stringstreams
for string to type and type to string conversions is described
here[
^]. See items:
39.1, 39.2 and 39.3. :)
If you read this items you will find out that stringstream conversion is not just an alternative to
atoi
. Using stringstreams you can convert an arbitrary type
T to string if provided
T supports syntax like
std::cout << x
. :)