Simple C++ problem????

Discussion in 'OT Technology' started by Kingfisher, Mar 7, 2006.

  1. Kingfisher

    Kingfisher Keepin L's lit

    Joined:
    Mar 29, 2003
    Messages:
    4,736
    Likes Received:
    0
    Location:
    Southern California
    I'm trying to find out whether the user is just pressing the ENTER button without any other info. Below is the code, and it won't work the way I want it to:

    ...blahblah code up here...
    char entry;
    cout << "Enter character: ";
    cin >> entry;
    if (entry != '\n' && entry !='Q' && entry!= 'q')
    return true;
    else
    cout << "\n*** Program Terminated ***" << endl;
    exit(0);
    }

    I know this is supposed to be real simple, but I have tried \n, /n, ' ', etc.. Any ideas?? :hs:
     
  2. Penguin Man

    Penguin Man Protect Your Digital Liberties

    Joined:
    Apr 27, 2002
    Messages:
    21,696
    Likes Received:
    0
    Location:
    Edmonton, AB
    On Windows, lines are terminated with \r\n, not just \n. Not sure whether this makes any difference for what you're trying to do, but it might.
     
  3. Kingfisher

    Kingfisher Keepin L's lit

    Joined:
    Mar 29, 2003
    Messages:
    4,736
    Likes Received:
    0
    Location:
    Southern California
    i tried \r\n and it still wont work. ... Help????

    it need to recognize that the user just hit enter without anythign else. isn't \n suffieicent??? i dont know whats wrong.
     
  4. peerk

    peerk New Member

    Joined:
    Mar 14, 2005
    Messages:
    984
    Likes Received:
    0
    I believe cin ignores whitespace by default.

    Code:
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
    	char entry;
    	cout << "Enter character: ";
    	cin.get(entry);
    
    	if (entry == '\n')
    		cout << "enter\n";
    	else
    		cout << "no enter" << endl;
    	
    }
    
    http://www.fredosaurus.com/notes-cpp/io/reading-chars.html
     
  5. Kingfisher

    Kingfisher Keepin L's lit

    Joined:
    Mar 29, 2003
    Messages:
    4,736
    Likes Received:
    0
    Location:
    Southern California
    Thank you peerk. I finally figured it out!! It was a combination of things, including leftover whitespaces from the code above this particular snippet of code. I realized I needed to use cin.get(entry); for this part and cin.ignore(); for the code above it. Thanks to everyone who put effort in this. I had to spent this whole day on this and finally got it working. :bigthumb:
     
  6. Penguin Man

    Penguin Man Protect Your Digital Liberties

    Joined:
    Apr 27, 2002
    Messages:
    21,696
    Likes Received:
    0
    Location:
    Edmonton, AB
    Ah, right, I remember that bullshit now.

    It's been a while since I've done C++, I'm so used to pure C now :embd:
     

Share This Page