PDA

View Full Version : Basic c++ programing question




ajunquerah
Dec 31, 2011, 04:10 AM
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:

#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.



jiminaus
Dec 31, 2011, 06:32 AM
If I add this after the first cin.sync():

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.

#include <iostream>
using namespace std;
int main (){
char c;
do {
cout << "Press a key" << endl;
cin.get(c);
if (c != '\n') {
while (cin.get() != '\n') { }
}
cout << "Key pressed : " << c << endl;
} while (c != '\n');
cout << "Press any key to continue...";
cin.get();
return 0;
}

ajunquerah
Jan 1, 2012, 02:45 AM
Thanks for your help.

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

I will do some investigations first.