Using an int or char

This is a discussion on Using an int or char within the C++ Programming forums, part of the General Programming Boards category; Ok, This is my problem, here is the question to better understand "Enter the length of a rectangle or enter ...

  1. #1
    cujo_77
    Guest

    Using an int or char

    Ok,
    This is my problem, here is the question to better understand "Enter the length of a rectangle or enter 'x' to exit" (when you exit you return to an earlier function, but that is not important). When the user enters a value for the square I need to use it for a mathmatical operations, obviously the int will not accept a char, but if I put a number in a char it will not work because a char has its own numerical value.

    Matt

    P.S. Thanks for the help with my "Stuck in a loop" problem.

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    A char is simply a smaller int, you can use an int like a char provided the value is consistent with the character set that you use. With appropriate casting, an int can be used as both an int and a char.

    -Prelude
    My best code is written with the delete key.

  3. #3
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    One option is to read the input as a string, then convert it to an int using atoi().
    Code:
       char str[15];
       int length;
    
       cout << "Enter the length of a rectangle (or 'x' to exit):";
       cin >> str;
       if (str[0] == 'x') return 0;
       length = atoi(str);
       cout << "length:" << length << endl;

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 48
    Last Post: 09-26-2008, 03: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, 08:36 PM
  3. Replies: 14
    Last Post: 06-28-2006, 01:58 AM
  4. Game Won't Compile
    By jothesmo in forum C++ Programming
    Replies: 2
    Last Post: 04-01-2006, 03:24 PM
  5. Contest Results - May 27, 2002
    By ygfperson in forum A Brief History of Cprogramming.com
    Replies: 18
    Last Post: 06-18-2002, 01:27 PM

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