#include <iostream>
#include <string>
using namespace std;
void doOneSet();
int main() {
srand(time(0));
doOneSet();
return 0;
}
void doOneSet() {
int answer;
for (int i = 0; i < 5; i++) {
cout << (rand() % 100) << " + " << (rand() % 101) << ": ";
cin >> answer;
}
}
The following code hangs, and never outputs the cout
statement, and also doesn't get the get the cin
statement. When I end the cin
statement as follows, it works fine, but I'm not sure why. I want to have the input on the same line, not on the next line.
cout << (rand() % 100) << " + " << (rand() % 101) << ": " << endl;
I've been able to do this easily before, but for some reason I'm having an issue now, not sure why. Thanks in advance!
I know this is old, but for future searchers, I just hit this issue. I was setting up a new PC and installed VS2019 then remembered I needed VS2013 installed too to support legacy builds. A simple Hello World app would hang on the cout.
I reran the VS2019 install as Repair and, following the reboot, cout behaves as expected.
I could not reproduce your behavior in g++ 4.9.4, but I have an idea. You could try using the fflush function which flushes the buffer of a stream. Here is the code:
#include <stdio.h>
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
void doOneSet();
int main() {
srand(time(0));
doOneSet();
return 0;
}
void doOneSet() {
int answer;
for (int i = 0; i < 5; i++) {
cout << (rand() % 100) << " + " << (rand() % 101) << ": ";
fflush(stdout);
cin >> answer;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.