Thread: Clearing a variable

  1. #1
    Registered User
    Join Date
    Sep 2006
    Location
    Kansas City
    Posts
    76

    Clearing a variable

    I have a simple code:
    Code:
    ...
    char yn_response;
    
    cout << "Input data form file ? (y/n)" << endl;
    cin >> yn_response;
    if ( yn_response == 'y')
       {
         // do something
       }
    
    cout << "Input data form keyboard ? (y/n)" << endl;
    cin >> yn_response;
    if ( yn_response == 'y')
       {
         // do something
       }
    ...
    The questions just keep on going. Now I would only like to use the yn_response variable for each question, so how can i clear its contents ?

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    In that code you don't really need to, since you are assigning a new value to it each time (although technically it might matter if some input error occurs).

    You cannot "clear" a char variable. All you can do is set it to whatever value you want. For example, you can set it to 'a' or ' ' or '\0' to indicate that it is "cleared". So if you want to set it to something other than 'y' or 'n', just assign the value you want to use.

    BTW, you aren't initializing yn_response in that code. When you first start, the value is not "cleared" it is uninitialized. It is generally whatever bits are in memory at that spot at that time. So if you want to clear it you should be initializing it with your "clear" value there as well.

  3. #3
    Registered User
    Join Date
    May 2006
    Posts
    169
    yn_response='\0';
    for example. but you dont really have to in your particular program, since you assign it a new value the second time you call cin

    edit: me too slow

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    cin >> yn_response;
    if ( yn_response == 'y')
    You should first check whether cin itself returned an error condition or not.

    If it does return error, then I don't know whether you should regard yn_response as "unchanged" (it's whatever it was last set to) or "undefined" (it could be anything at all)
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 10
    Last Post: 09-27-2005, 12:49 PM
  2. Replies: 2
    Last Post: 04-12-2004, 01:37 AM
  3. write Variable and open Variable and get Information
    By cyberbjorn in forum C++ Programming
    Replies: 2
    Last Post: 04-09-2004, 01:30 AM
  4. Variable question I can't find answer to
    By joelmon in forum C++ Programming
    Replies: 3
    Last Post: 02-12-2002, 04:11 AM
  5. clearing a variable
    By Unregistered in forum C Programming
    Replies: 4
    Last Post: 02-09-2002, 03:49 PM