Problem with Casting.

This is a discussion on Problem with Casting. within the C++ Programming forums, part of the General Programming Boards category; #include <iostream.h> #include <stdlib.h> int main() { int j; char k[4]= "123"; j = static_cast<int>( k[0]); cout<<j<<endl; system("PAUSE"); return 0; ...

  1. #1
    Registered User
    Join Date
    Oct 2001
    Posts
    10

    Question Problem with Casting.

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

    int main()
    {
    int j;
    char k[4]= "123";

    j = static_cast<int>( k[0]);
    cout<<j<<endl;


    system("PAUSE");
    return 0;
    }
    I am writing a program where i receive a string with numbers in it. My program has to validate those numbers. I try to cast the numbers to an intiger for easier validation.
    This program will run om win. using Borland.
    The problem i'm having is that j contains the dec value of of 1.
    I want j to comtain the number 1 not the decimal value of 1.
    How do i do that.
    #include <iostream.h>
    void main(void){
    char t[7] = "Thanks";

    cout<< t <<endl;
    }

  2. #2
    Registered User jasrajva's Avatar
    Join Date
    Oct 2001
    Posts
    99
    The problem i'm having is that j contains the dec value of of 1.
    no it doesnt it will contain the ascii value
    what you want is the decimal value which is 1 itself;

    so do

    Code:
    j = static_cast<int>( k[0]) - '0';
    btw the decimal value of is 1

  3. #3
    Registered User
    Join Date
    Nov 2001
    Posts
    3

    Ascii numbers

    This is not a real problem.

    In ascii 48 - 57 = 0 - 9

    so one easy thing to do is this.
    You don't even need the static cast.

    1: char t;
    2: int k;
    3: t = 5;
    4: k = (int)t;


    now k will equal 53 because 48 + 5 is 53

    What I do to check is just check if the char value is between 48 and 57.

    now if you want the integer value to be the same as the number in the character replace line four with this.
    k = (int)t - 48.

    If you need to include decimal numbers you must also check if a character is equal to 46 which is the '.' character

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Laptop Problem
    By Boomba in forum Tech Board
    Replies: 1
    Last Post: 03-07-2006, 06:24 PM
  2. type casting problem?
    By lackofcolour in forum C Programming
    Replies: 6
    Last Post: 01-30-2006, 04:29 PM
  3. Replies: 5
    Last Post: 11-07-2005, 11:34 PM
  4. half ADT (nested struct) problem...
    By CyC|OpS in forum C Programming
    Replies: 1
    Last Post: 10-26-2002, 09:37 AM
  5. binary tree problem - help needed
    By sanju in forum C Programming
    Replies: 4
    Last Post: 10-16-2002, 06:18 AM

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