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:

#include<iostream.h>
#include<stdlib.h>

main()
{
  char x[10];
  int y;
  char opt;
  do
  {
  cout<<"Enter your string"<<"\t";

       cin>>x;

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

  }  
  else      {     
                y=atoi(x);

            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";
    cin>>opt;  


 }      
   while(opt=='y'||opt=='y');         
  system("pause");
}

Recommended Answers

All 2 Replies

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);

what is the number 45 21? What should the putput be when you enter 45 21?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.