Convert from char to int

This is a discussion on Convert from char to int within the C++ Programming forums, part of the General Programming Boards category; how can i convert from char to int? I keep getting errors, or the conversion changes the number. etc. char ...

  1. #1
    Nerd Xmevs's Avatar
    Join Date
    Apr 2002
    Posts
    146

    Convert from char to int

    how can i convert from char to int? I keep getting errors, or the conversion changes the number.

    etc.

    char cVar = '1';
    int nVar = (int)cvar;

    now...

    int == 6532465

    why???

  2. #2
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    A char is one byte. This means it can hold a maximum value of 2^8 or 128 if signed, 256 if unsigned.
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  3. #3
    I'm Back
    Join Date
    Dec 2001
    Posts
    556
    what you are doing will put the ascii val of cVar into nVar


    use atoi() in stdlib.h for converting the numerical value in char into an integer.


    Code:
    char *c="12345";
    int i;
    
    i=atoi(c);
    
    cout<<"I is : "<<i;

  4. #4
    Nerd Xmevs's Avatar
    Join Date
    Apr 2002
    Posts
    146
    oh, ok... thanks.

  5. #5
    Registered User
    Join Date
    May 2002
    Posts
    66

    ASCII char to int

    Since you are using char to describe it, I would assume you want '0'..'9' in int form, then a simple thing is:
    Code:
    char c = '2';
    int ic = (int)(c - '0');
    For a string that represents a number, example above is good.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 48
    Last Post: 09-26-2008, 04:45 AM
  2. can some one please tell me the cause of the error ?
    By broli86 in forum C Programming
    Replies: 8
    Last Post: 06-26-2008, 09:36 PM
  3. Replies: 8
    Last Post: 03-10-2008, 12:57 PM
  4. How do i un-SHA1 hash something..
    By willc0de4food in forum C Programming
    Replies: 4
    Last Post: 09-14-2005, 06:59 AM
  5. easy if you know how to use functions...
    By Unregistered in forum C Programming
    Replies: 7
    Last Post: 01-31-2002, 07:34 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21