scanf("%d", &time); // 讀取整數
while ((temp = cin.get()) != '\n') { // 企圖讀取整行字符串
str += temp;
}
現象:循環直接結束,cin.get() 讀到的是 scanf 遺留在緩沖區的換行符 '\n'。
scanf("%d", &time) 讀取數字後,緩沖區仍保留用戶按下的回車符(\n)。隨後 cin.get() 讀取該殘留換行符,滿足循環結束條件,導致實際字符串輸入被跳過。
scanf("%d", &time);
fflush(stdin); // Windows/MSVC 有效,非標準
// 或跨平台:
int c;
while ((c = getchar()) != '\n' && c != EOF);
cin.ignore(numeric_limits::max(), '\n'); // 需 #include
int time;
cin >> time;
cin.ignore(); // 忽略單個換行符
string str;
getline(cin, str); // 直接讀取整行
項目中統一使用 C++ iostream(cin/cout/getline),避免混用 C 的 scanf/printf 導致緩沖區同步問題。