Thread: type casting

  1. #1
    Registered User
    Join Date
    Dec 2002
    Posts
    4

    Question type casting

    ref: type casting

    i want to write a program to enter a integer eg 1200, find its reverse and the subtract the orignal value from the reverse ie 1200-0012.

    i try to enter the code and give me and error message. Can any one please help me to solve the problem:

    int subtract(int year)
    //find the reverse of the year, the difference between the original year &
    //reverse year eg 1999-9991
    {
    int len;//string length
    int i;
    int diff;//absolute difference
    int rYear;//reverse year
    string sYear;//turn year into string

    //change year into string and find its reverse order
    sYear = year;
    len = sYear.strlen();
    i = sYear.strlen()-1;//set i = length of string-1

    while (i>=0)
    {
    sYear.at(i);
    i--;
    }//end loop

    //type cast
    rYear = int(sYear);

    //change string back into integer
    diff = fabs(year - rYear);
    return diff;
    }//end diff

  2. #2
    Registered User Codeplug's Avatar
    Join Date
    Mar 2003
    Posts
    4,981
    Read this

    How are you trying to reverse the string? What are you trying to achieve by calling "sYear.at(i);"?

    Also, the string type does not know how to convert to and from int. You need to use istringstream to do that (search the board for many examples).
    You might want to get your code to compile and execute before you start working on the logic.

    fabs() is for floating point numbers - there is no reason to use it with ints.

    gg

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. What dose this type casting mean??
    By zhoufanking in forum C Programming
    Replies: 4
    Last Post: 06-11-2008, 06:09 AM
  2. Replies: 0
    Last Post: 03-20-2008, 07:59 AM
  3. pointer to array of objects of struct
    By undisputed007 in forum C++ Programming
    Replies: 12
    Last Post: 03-02-2004, 04:49 AM
  4. Erros in Utility Header File
    By silk.odyssey in forum C++ Programming
    Replies: 4
    Last Post: 12-22-2003, 06:17 AM
  5. help with simple type casting problem
    By Jeremy_S in forum C Programming
    Replies: 2
    Last Post: 02-27-2002, 12:38 PM