I’m not new to programming, but I am relatively new to C++. I would like to distribute simple console applications so I can help others as I learn. The vast majority of machines on the campus of my university are windows based, and have the Borland compiler installed by default. I prefer to do my development on a Linux-based system with g++ and other tools. So I’d like to add some cross-platform way of leaving the program running until the user presses enter. That way, the user is able to view the output even if he or she double clicked on the exe rather than running it in the console in windows. To do this, I wrote something similar to:
#include <iostream>
using namespace std;
int main()
{
float val1, val2;
bool wait = true;
cout << "Please enter the first value to add: ";
cin >> val1;
cout << "Please enter the second value to add: ";
cin >> val2;
cout << "Result: " << val1 + val2 << endl << endl;
cout << "Press enter to exit...";
while (wait)
{
if (cin.get() == '\n')
wait = false;
}
return 0;
}
Using the code above, the program exits after displaying the result. However, if you comment out the cin calls, it works as expected. This leads me to believe that cin.getline is picking up my enter key press from my last data entry. I suspect this is due to the tightness of the loop. I have learned that there is no cross-platform sleep function in C++, so that is not an option. What else can I do to make this work?
You can add
or
before you call
cin.get(). This will ignore the newline left from the user entering the second number or all the characters in the buffer until a newline.Also you neither need to compare the return value of
getto'\n'nor put it in a loop. The user has to hit enter forgetto return, soIs sufficient.
What happens if you do
Is that the loop is entered, and
cin.get()is called. The user can enter any amount of text at the console as he wants. Say they enteredin the console. Then the user presses the Enter key.
cin.get()returnsH, andello\nis still left in the buffer. You compareHwith\nand see that they are not equal, continue the loop.cin.get()is called and since there is already text in the buffer, returnseimmediately. This loop continues wasting time until it gets to the last character of the buffer which is\nand it compares true with\nso the loop breaks. As you can see, this is a waste of time.If you do put
cin.get()in a loop and compare the return value of it with\n, there is also the danger ofcincoming to an end-of-file before an\nis encountered. I believe the effect of this on your program would be an infinite loop, but I’m not sure since I can’t try it on Windows.Also, even though you don’t need to use a loop in the first place, you are wasting even more time with a
boolbecause you could reduce the loop to