※ 引述《tonyder.bbs@bbs.yuntech.edu.tw (綺緣)》之銘言:
> void main(void)
> {
> int a;
> do
> {
> cin.clear();
> cin>>a;
> }while(cin.good()==0);
> }
> 請問一個很基礎的問題
> 如果想限制只能輸入數字要怎麼改寫這個程式(只要輸入abc就會當掉)
> 自己測試的結果
> 如果使用迴圈測試cin是否錯誤
> 第一次錯誤接著就不會執行cin這行
> 所以就變成無窮迴圈了
> 請問有其他解決的辦法媽
不知道下面的寫法是否可以決解您的問題...
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
int a;
string strtmp;
bool check;
while(cin >> strtmp)
{
check = true;
for(int i=0;i < strtmp.size();i++)
{
if(!isdigit(strtmp[i]))
{
check = false;
break;
}
}
if(check)
{
istringstream istr(strtmp);
istr >> a;
cout << "輸入的整數是:" << a << endl;
}
else
cout << "不是整數!" << endl;
}
}
--
● ˙ ˙ ◢▇◣ ◢▇◣ ▇ ▇ █▇◣ █▇◣ █▇◣ ◢▇◣ █▇▉ /
˙ ╲ █ █ █ █ █ ▉ █ ▉ █▆ █▆▉ ▉▉▉ ★
◢ ★˙ ◥█◤ ◥█◤ ◥█◤ ██◤ █◥▆ █▆◤ █ ▉ ▉▉▉˙ ◣
CDBBS 中正築夢園BBS站 歡迎蒞臨參觀 cd.twbbs.org (140.123.20.230)
http://cd.twbbs.org◥ * Author: wrj ★ From: 218.172.94.141 ◤