Basic c++ programing question

Discussion in 'Mac Programming' started by ajunquerah, Dec 31, 2011.

  1. ajunquerah, Dec 31, 2011
    Last edited by a moderator: Dec 31, 2011

    macrumors newbie

    #1
    Hi.
    I'm new in the forum.
    I was testing Xcode, and others IDE like eclipse, in my new Mac with the following c++ code:
    Code:
    #include <iostream>
    using namespace std;
    int main (){
       char c;
       do {
          cout << "Press a key" << endl;
          cin.get(c);
          cin.sync();
          cout << "Key pressed : " << c << endl;
       }while (c != '\n');
       cout << "Press any key to continue...";
       cin.sync();
       cin.get();
       return 0;
    }
    The question that this piece of code does not work as do in Windows-Visual C++ environment. In particular the cin.get(c) inside the do construction does not allow me to enter a character in the keyboard in the second time and the programs goes into a loop.

    I'm compilig this code with gcc compiler.

    I'm sure is a well known issue in the Mac comunity so thanks in advance for who give me some indications.
     
  2. macrumors 65816

    jiminaus

    #2
    If I add this after the first cin.sync():
    Code:
    if (cin.bad()) {
    	cout << "cin has bad bit set. Aborting.";
    	return -1;
    }
    
    I do get "cin has bad bit set. Aborting." in the output. Looks like calling sync on cin under Mac OS X makes cin go bad. Calling get(char&) on a bad istream won't change the referenced char, hence the infinite loop.

    What can you do? Don't try to use sync to discard the input up to and including the newline. Instead do it in a loop.
    Code:
    #include <iostream>
    using namespace std;
    int main (){
    	char c;
    	do {
    		cout << "Press a key" << endl;
    		cin.get(c);
    		[COLOR=red]if (c != '\n') {
    			while (cin.get() != '\n') { }
    		}[/COLOR]
    		cout << "Key pressed : " << c << endl;
    	} while (c != '\n');
    	cout << "Press any key to continue...";
    	cin.get();
    	return 0;
    }
    
     
  3. macrumors newbie

    #3
    Thanks for your help.

    This only means that my knowlege is very, very limited.

    I will do some investigations first.
     

Share This Page