-1

First, here is the code:

using namespace std;
cout << "\aOperation \"HyperHype\" is now activated!\n";
cout << "Enter your agent code:_______\b\b\b\b\b\b\b";
long code;
cin >> code;
cin.get();
cout << "\aYou entered " << code << ".....\n";
cout << "\aCode verified! Proceed with Plan Z3!\n";
cin.get();

return 0;

It compiles without a problem and runs almost without flaw; after 'code' receives its value from standard input, the final string flashes up for maybe a millisecond and the program dies. As you can see I placed the 'cin.get()' member function after the final string in order to prevent this, yet it continues to die after the 'cin >> code;' line.

This method has worked for all of my other practice programs up until now, and there is nothing structurally different between this program and any of the others.

Any suggestions?

(Assume proper header files and preprocessor directives are in place.)

akuryo
  • 1

2 Answers2

3

You are reading the newline character you already entered earlier with your final get() call. You might want to ignore all characters up to and including the first newline before waiting for some other input:

std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cin.get();

You can shorten this to become

std::cin >> std::ws;

if it is OK requiring to enter a non-whitespace character to terminate the program: the std::ws manipulator extracts whitespace characters until either a non-whitespace character or the end of the stream is reached.

Note that std::istream::get() actually does work as it should! It just reads the next character. It just happens not to do what you did expect.

Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
  • 1
    Shouldn't [`std::ws`](http://en.cppreference.com/w/cpp/io/manip/ws) skip the newline as well, making the `ignore` redundant? – Mark Ransom Jan 09 '14 at 22:31
  • @MarkRansom: actually, you are right: there isn't any need to extrac the already entered character (corrected). Thanks! – Dietmar Kühl Jan 09 '14 at 22:33
0

Add a cin >> code line instead of the two cin.get(). If the program just closes anyway, then this would probably be the simplest thing to do.

Seldom
  • 259
  • 2
  • 4
  • 14