C++——回答問題

1.

#include <iostream>

#include <string>
using namespace std;


bool accept()
{
cout<<"Do you want to proceed (y or n)?\n";//寫出提問
char answer =0;
cin >> answer;//輸入回答
if (answer=='y')return true;//若回答y,返回true
else
return false;///否則返回false
}
int main()
{
cout<<accept();//輸出結果
std::cin.ignore(std::cin.rdbuf()->in_avail()+1);
return 0;

}


2.

#include <iostream>
#include <string>
using namespace std;


bool accept()
{
cout<<"Do you want to proceed (y or n)?\n";//寫出提問
char answer =0;
cin >> answer;//輸入回答
switch(answer){
case 'y':return true;break;
case 'n':return false;break;
default:cout<<"I'll take that for a no.\n";
return false;
}
}
int main()
{
cout<<accept();//輸出結果
std::cin.ignore(std::cin.rdbuf()->in_avail()+1);
return 0;
}

3.

#include <iostream>
#include <string>
using namespace std;


bool accept()
{
int time =4;
cout<<"Do you want to proceed (y or n)?\n";//提出問題
while(time>=1){//輸入次數爲三次
char answer =0;
cin>>answer;//輸入問題
switch(answer){
case 'y':return true;
case 'n':return false;
default:cout<<"Sorry,I don't understand that .\n";//不是y和n,可再次輸入
time--;//輸出次數+1
cout<<"you have only "<<time<<" chance.\n";
}
}
cout<<"you have only "<<time<<" chance.\n";
cout<<"I'll take that for a no.\n";//輸入次數超過3次後,認爲是false
return false;
}
int main()
{
cout<<accept();//輸出結果
std::cin.ignore(std::cin.rdbuf()->in_avail()+1);
return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章