david870620 稍嫌羞澀的路人
註冊時間: 2011-02-11 文章: 3 來自: 地球 69.41 果凍幣
|
發表於: 2011-3-8, PM 10:53 星期二 文章主題: [C++]請問cin.get() |
|
|
請問一下:
為什麼我用cin.get()去讀取字元,我故意同時輸入很多字元時,進入無限迴圈??
照理來說 cin.get()應該只會讀取所輸入的第一個字元,為什麼會產生和cin >>一樣的問題?
順便附上發生錯誤的檔案原始碼:
代碼: | #include <iostream>
#include <cstdlib>
#include <cctype>
#include <ctime>
using namespace std;
int Two_of_one (char*, char*);
int answer, upper = 100, lower = 1;
int main ()
{
char Tryagain;
char name1[100];
char name2[100];
cout << "請輸入<玩家1>的名字:" << endl;
cin.getline(name1, 100);
cout << "請輸入<玩家2>的名字:" << endl;
cin.getline(name2, 100);
do
{
srand (time(NULL));
answer = (rand ()%98)+2;
cout << "答案不包括1、100這兩個數字" << endl;
for (int Result = 0;;)
{
Result = Two_of_one(name1, name2);
if (Result != 0) break;
Result = Two_of_one(name2, name1);
if (Result != 0) break;
}
upper = 100; lower = 1;
cout << "再來一局?(y):" ;
cin.get();
cin.get(Tryagain); // <----------就是這裡
} while (Tryagain == 'Y');
return 0;
}
int Two_of_one (char* name1, char* name2)
{
int player_ans;
cout << "目前數字範圍: " << lower << "~" << upper << endl
<< "<" << name1 << ">請輸入"<< lower << "~" << upper << "的數字:" << endl;
cin >> player_ans;
if( cin.fail() )
{
cin.clear();
char ch1;
cin >> ch1;
cout << "錯誤型態的輸入!" << endl;
}
while (player_ans >= upper || player_ans <= lower)
{
cout << "<" << name1 << ">你輸入了不合規定的數字,請重新輸入!" << endl
<< "<" << name1 << ">請輸入"<< lower << "~" << upper << "的數字:" << endl;
cin >> player_ans;
}
if (player_ans == answer)
{
cout << "答案正是:" << answer << " 抱歉,<" << name1 << "> 你輸了! 恭喜<" << name2 << " >!你贏了這場比賽!" << endl; return 1;
}
else if (player_ans > answer)
{
upper = player_ans; return 0;
}
else
{
lower = player_ans; return 0;
}
}
|
|
|