Hi to all!. I have wrote a program which converts character numeric value into integer numeric value by using function atoi(string).
For example if i write 45 then it gives output :"after conversion from ascii to integer, value is 45." or if i write 4521 it gives output:"after conversion from ascii to integer value is 4521".My program is runnig perfectly, but there is a problem that when i give space in my interger e.g 45 21, then program displays 45 only and not 21. so what is the solution for this and also tell me that which header file should be included for declaration of string data type? My code for this program is as follows:


  char x[10];
  int y;
  char opt;
  cout<<"Enter your string"<<"\t";


     if(atoi(x)==0)   // this function converts a character numeric value into interger numerical value
    cout<<"you can only enter numeric values"<<endl;

  else      {     

            cout<< "after conversion from ascii to integer ,  value is" <<y<<endl<<endl;
    cout<<"do you want to continue? Press Y for Yes and N for No";

2 Years
Discussion Span
Last Post by NathanOliver

This is as expected. The atoi() function stops at the first non-numeric character in the string, which would be the space. You can use the strtol() (string-to-long) function which allows you to pass the address of a char pointer which will be set with the location of the space in the original string, so you can continue processing as needed. More logic will be required for you to handle this appropriately, naturally.

BTW, I am trying to teach you how to fish, and not just give you one... :-) In any case, the proper signature for strtol() is this: long int strtol(const char *nptr, char **endptr, int base);

Edited by rubberman

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.