Thread: question about the loop in case conversion program

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by Elhaz
    In Herbert Schildt's
    How many people just cringed and stopped reading there?

    *raises hand*

    Quzah.
    Hope is the first step on the road to disappointment.

  2. #2
    Registered User
    Join Date
    Nov 2002
    Posts
    126
    I've got a little tip for you to make your algorithm much cleaner. In ASCII code, the only difference between a letter and the same letter of the opposite case is the fifth bit of the character. Upper case numbers have a fifth bit value of 0, lower case of 1, and the rest of the bits are the same. So to change the case of a letter, all you need to do is flip the fifth bit of the number. How do you do that? With the binary exclusive OR operator (^). If you don't know about binary operators or the exclusive or operation, look them up. At any rate, here's my revision of your code:

    Code:
    // C++ A Beginer's Guide - Herbert Schildt
    // Module 3 Mastery Check Question # 11
    
    // Case Converter
    
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
    	cout << "Case Converter\n\n";
    	cout << "Please type something (enter a \'.\' to quit):\n\n";
    
    	char input;
    	int caseCounter = 0;  // records number of coversions
    
    	while (input != '.')
    	{
    		cin >> input;
    
    		if( input >= 'A' && input <= 'z' )
    		{
    			input ^= 1 << 5; //Flip the fifth bit of the char
    			caseCounter++;
    		}
    		
    		cout <<input;
    	}
    	
    	cout << "\n\nThe number of case changes was: " 
                    << caseCounter << "\n\n";
    }
    Oooh, clean. If you didn't know, the << operator is used as the binary shift operator(google it )

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. get keyboard and mouse events
    By ratte in forum Linux Programming
    Replies: 10
    Last Post: 11-17-2007, 05:42 PM
  2. Intel syntax on MinGW ?
    By TmX in forum Tech Board
    Replies: 2
    Last Post: 01-06-2007, 09:44 AM
  3. ascii rpg help
    By aaron11193 in forum C Programming
    Replies: 18
    Last Post: 10-29-2006, 01:45 AM
  4. Replies: 27
    Last Post: 10-11-2006, 04:27 AM
  5. rand()
    By serious in forum C Programming
    Replies: 8
    Last Post: 02-15-2002, 02:07 AM