atoi conversion problem

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • fantastic4
    New Member
    • Apr 2010
    • 2

    atoi conversion problem

    Following code is not working properly
    it give answer
    c=5
    and
    d=75

    Code:
    char a='5',b='7';
    int c,d;
    c=atoi(&a);
    cout<<c;
    d=atoi(&b);
    cout<<d;
  • jkmyoung
    Recognized Expert Top Contributor
    • Mar 2006
    • 2057

    #2
    Seems like it's looking at the address and expecting a string; however you have only defined space for characters.
    In memory, it must be stored as
    75\0.

    Use strings instead of single chars, or you could also try c=(int)(a - '0');
    since you know both a and b are chars.

    Comment

    • donbock
      Recognized Expert Top Contributor
      • Mar 2008
      • 2427

      #3
      Refer to the man page for atoi. As jkmyoung said, atoi expects its argument to point to a null-terminated string. That's not what you passed. It is amazing the result bears any resemblance to what you expect.

      Comment

      • whodgson
        Contributor
        • Jan 2007
        • 542

        #4
        The following may shed some further light on it.
        Code:
        const char* s="  21xy 3";
            const char*s1= " 74.7xyz ";
            cout<<"the first string is \n"<<s<<endl;
            cout<<"the second string is \n"<<s1<<endl;
            n=atoi(s);
            m=atoi(s1);
            cout<<"after converting strings to integers ";
            cout<<"s= "<<n<<" and s1="<<m<<endl;
            cout<<"the product of s and s1 is "<<n*m<<endl;
        //prints:-
        /*demonstrating the atoi() function
        the first string is
        21xy 3
        the second string is
        74.7xyz
        after converting strings to integers s= 21 and s1=74
        the product of s and s1 is 1554
        press any key to continue...*/

        Comment

        • whodgson
          Contributor
          • Jan 2007
          • 542

          #5
          The following convert() function I think does the equivalent of atoi ().
          Code:
          double convert(string a)
          {double sum_s=0.0;
              double xx=0.0;
              len=a.length();
              n=len;
              xx=pow(10,n-1);
              for(int i=0;i<len;i++)
              {
              sum_s+=(a[i]-'0')*xx;
              xx/=10;
              }
              return sum_s;
          }

          Comment

          Working...