Reputation: 432
So I've taken up the task of learning C++ in my spare time (Web Developer by trade, so I'm not completely oblivious to code).
#include <iostream>
#include <windows.h>
using namespace std;
/*
*
*/
int main(int argc, char** argv) {
string response;
cout << "Would you like to buy some bread? : " << flush;
getline(cin, response);
if (response == "yes" || response == "y" || response == "Yes" || response == "Y") {
cout << "\nYou have successfully bought some bread\nThanks." << endl;
Sleep(2000);
return 0;
}
else if (response == "no" || response == "n" || response == "No" || response == "N") {
cout << "\nYou didn't buy some bread.\n" << endl;
}
string second_response;
cout << "Would you like to go back and buy some bread? : " << flush;
getline(cin, second_response);
if (second_response == "yes" || second_response == "y" || second_response == "Yes" || second_response == "Y") {
cout << "\nYou have successfully bought some bread 2nd time round";
Sleep(2000);
}
else
{
cout << "\nMaybe next time?";
Sleep(2000);
}
return 0;
}
As you can see, it just asks the person dependent on their answer if they'd like to buy bread (i'm not very imaginative).
The problem is, that the sleep function appears to be working but incorrectly in the string second_response part, what happens is that it waits for 2000 milliseconds and then outputs text when it's meant to be the other way round?
I've been on google looking for an answer but I thought it would be better to come on here so i can actually phrase what's going wrong correctly.
Thanks guys!
Upvotes: 1
Views: 1539
Reputation: 14386
You may be falling victim to buffering.
Between a program writing characters to STDOUT and text actually appearing on the screen, there are various layers of processing, some of which try to optimize the overall throughput of the system by combining I/O operations until a certain amount of data is available. For instance, characters are often not printed until some buffer size is exceeded, or until a newline is encountered.
Note that your question begins with a newline but doesn't end with one. What you may be seeing is that the program writes the characters, the terminal driver buffers them, then the program sleeps, and when the program exits, the OS automatically flushes all streams so that you finally see the previous line of output.
There are various ways of forcing output to appear immediately; using newlines is only one of them. Look up 'buffering' and 'cout' and you will find more solutions.
Upvotes: 4