Click here to Skip to main content
15,881,281 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C++
#include "stdafx.h"
#include <stdlib.h>
#include <iostream>
#include <string>
using namespace std;
//#include <stdlib.h>   // for itoa() call
//#include <stdio.h>    // for printf() call
int main() 
{
    string strConvert;
    cout<<"sentence"<<endl;
    cin>>strConvert;
    int intReturn;
    intReturn = atoi(strConvert.c_str());
    cout<<intReturn<<endl;
}
Posted
Updated 13-Feb-11 21:29pm
v3

When I execute your program it gives me right result.
As MSDN says :

If the input cannot be converted to a value of that type, the return value is 0
 
Share this answer
 
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:
C++
int intReturn;
if(std::cin >> intReturn)
{
    // We will get here only if the input is valid integer
    std::cout << intReturn;
}


For a conversion from string to int you can also use (as an alternative to atoi):
C++
std::string str = "567";
std::istringstream iss(str);
int intReturn;
if(iss >> intReturn)
{
    // We will get here only if the conversion is successful
    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. :)
 
Share this answer
 
Comments
ShilpiP 14-Feb-11 3:26am    
Good Answer :). Have 5 ...
Nuri Ismail 14-Feb-11 3:34am    
Thank you! I believe that your answer points the actual problem of the OP and I voted 5 for it.
I just wanted to show some alternatives that the OP can use now and/or in future or never. :)

ShilpiP 14-Feb-11 3:44am    
Yes I also thought about stringstream as I commonly used it but I just explain him his problem and you think out of the box and give him another solution.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900