我正在制定一个程序,提示用户输入参加比赛的参赛者的名字和评委的分数。所有这一切都在一个for循环中,有一个计数器来跟踪参赛者的数量。由于参赛者的数量未知,用户应该输入“完成”。退出循环。
我发现退出循环的所有方法都是使用布尔值,它不适用于' string'变量。 我想知道是否有办法通过输入单词' Done'
来退出循环#include <iostream>
#include <string> //for name entry of contestants
#include <iomanip> //rounding and point perceision
#include <fstream> //write names and averages to a file for storage
using namespace std;
double calcAvgScore(int, int, int, int, int); //calculates the average after the highest and lowest scores are found
double findHighest(int, int, int, int, int); //finds the highest of the 5 scores
double findLowest(int, int, int, int, int); //finds the lowest of the 5 scores
int main()
{
string cName; //name of the contestant
int jScore1, jScore2, jScore3, jScore4, jScore5; //scores of each judge
double AvgScore; //average of the scores
ofstream outFile;
outFile.open("NamesAndAverage.txt");
for (int count = 1;; count++)
{
if (count = 1)
cout << "Please enter the name of Contestant #" << count << ". If there are no Contestants enter ""Done""";
else
cout << "Please enter the name of Contestant #" << count << ". If there are no more Contestants please enter ""Done""";
cin >> cName;
}
}
答案 0 :(得分:1)
你可以break
退出循环:
for (int count = 1;; count++)
{
// prompt for input, snipped
cin >> cName;
if (cName == "Done")
{
break;
}
}
答案 1 :(得分:1)
您可以使用break;
:
if (cName == "Done") {
break;
}
此外,您的计划还有另一个错字。与
if (count = 1)
您实际上每次都会将count
重置为1。这应该是:
if (count == 1)
答案 2 :(得分:1)
您可以将条件直接添加到循环中,
for (int count = 1; cName != "Done"; count++)
或在循环中使用if
和break
。
if( cName == "Done" )
break;
您还可以在循环内容中使用三元:
cout << "Please enter the name of Contestant #" << count << ". If there are no" << (count > 1) ? "more" : "" << "Contestants enter ""Done"";
cin >> cName;
答案 3 :(得分:1)
除了处理"Done"
之外,您应该检查输入和输出操作是否成功,两者都可以使用if
/ else
语句完成:
if (std::ofstream outFile("NamesAndAverage.txt"))
for (int count = 1;; count++)
{
cout << "Please enter the name of Contestant #" << count << "."
"If there are no ";
if (count > 1) std::cout << "more ";
std::cout << "contestants enter \"Done\"\n";
if (cin >> cName && cName != "Done")
// use cName...
else
break;
}
else
std::cerr << "unable to open output file\n";