我将如何使用if..else,do..while?
此程序应提示用户输入大学名称并输出大学的排名,如果用户输入的名称不正确,程序应输出一条消息,表明输入的名称不正确。
#include <iostream>
#include <string>
using namespace std;
int main()
{
string college[] = {"Baylor", "Colorado", "Iowa State",
"Kansas", "Kansas State", "Missouri",
"Nebraska", "Oklahoma", "Oklahoma State",
"Texas", "Texas A&M", "Texas Tech"};
int conferenceRanking[] = {12, 11, 10, 9, 5, 8,
3, 2, 7, 1, 6, 4};
for (if)
{
cout << "Enter the name of a Big Twelve College: " << college[count]
<< college << "\n's ranking is " << conferenceRanking[count]
<< "\n" << endl;
}
return 0;
}
[样本]这是我想要的输出
Enter the name of a Big Twelve College: Nebraska
Nebraska's ranking is 3
答案 0 :(得分:0)
我会采用更复杂的方式并使用地图来保存数据并从命令行std :: getline获取学院,因为它会检测空格并将它们放入字符串中。阅读完名称之后,它会迭代已经创建的地图,找到我们正在寻找的大学。然后检查迭代器是否被找到!您应该查看一些C ++教程或一本好书来学习C ++的基础知识。
(这种方法使用C ++ 11标准,因此请确保您的编译器兼容)
#include <iostream>
#include <string>
#include <map>
int main()
{
std::map<std::string, int> colleges = {
{"Baylor", 12},
{"Colorado", 11},
{"Iowa State", 10},
{"Kansas", 9},
{"Kansas State", 5},
{"Missouri", 8},
{"Nebraska", 3},
{"Oklahoma", 2},
{"Oklahoma State", 7},
{"Texas", 1},
{"Texas A&M", 6},
{"Texas Tech", 4}
};
std::cout << "to end enter: exit";
bool p = true;
while(p){
std::string name;
std::cout << "Enter the name of a Big Twelve College: ";
std::getline(std::cin, name);
if(name == "exit"){
p = false;
break;
}
std::map<std::string, int>::iterator it = colleges.find(name);
if (it != colleges.end()){
std::cout << it->first << "'s ranking is " << it->second << "!" << std::endl;
}else{
std::cout << "No college found!, try again!" << std::endl;
}
}
return 0;
}
答案 1 :(得分:0)
您可以使用地图来保存您的排名,这将有助于您轻松地按名称访问您的排名。 您还可以保留一个布尔变量,指示当前用户输入是否存在于您的列表中,并使用它来决定用户是否应该获得他/她的答案,或者再次提示您输入一些大学名称。
以下是一个示例主要功能:
#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;
int main()
{
std::unordered_map<std::string, int> collegeRanks = {
{"Baylor",12},
{"Colorado",11},
{"Iowa State",10}
};
//etc...
bool finished = false;
string userInput;
while(!finished){
cout << endl << "Enter the name of a Big Twelve College: ";
getline (std::cin,userInput);
std::unordered_map<std::string,int>::const_iterator nameAndRank = collegeRanks.find (userInput);
if ( nameAndRank == collegeRanks.end() ){
// Not found :(
finished = false;
cout << endl << userInput << " does not exist in our database... try another college name!" << endl;
userInput = "";
}
else{
// Found :)
finished = true;
cout << userInput << "'s rank is " << std::to_string(nameAndRank->second) << endl;
}
}
return 0;
}
答案 2 :(得分:0)
您只需使用您拥有的阵列即可,而无需使用地图(如果您愿意)。请考虑以下代码。
bool has = false;
cout << "Enter college name\n";
string name;
cin >> name;
for(int i=0; i<12; i++){
if(college[i].compare(name) == 0){
has = true;
cout << "Ranking of " << college[i] << " is " << conferenceRanking[i];
}
}
//check if the name entered by user exists
if(has == false)
cout << "The college name entered does not exist";
bool
变量has
确定用户输入的大学名称是否存在于数组college[]
中。如果找到匹配项,则has
的值将更改为true
。