[英]C++ cout then cin hanging
#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;
}
}
以下代碼掛起,從不輸出cout
語句,也沒有得到 get cin
語句。 當我按如下方式結束cin
語句時,它工作正常,但我不確定為什么。 我想在同一行輸入,而不是在下一行。
cout << (rand() % 100) << " + " << (rand() % 101) << ": " << endl;
我以前很容易做到這一點,但由於某種原因,我現在遇到了問題,不知道為什么。 提前致謝!
我知道這是舊的,但對於未來的搜索者,我只是遇到了這個問題。 我正在設置一台新 PC 並安裝了 VS2019,然后想起我也需要安裝 VS2013 以支持舊版構建。 一個簡單的 Hello World 應用程序將掛在 cout 上。
我將 VS2019 安裝重新運行為修復,並且在重新啟動后,cout 的行為符合預期。
我無法在 g++ 4.9.4 中重現您的行為,但我有一個想法。 您可以嘗試使用刷新流緩沖區的fflush函數。 這是代碼:
#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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.