我的while循环打破循环时遇到了一些麻烦。如果我第一次正确回答问题,它允许我继续完成该程序。但是,如果我使用整数它会循环false,即使我在循环中正确回答它也不会退出并保存字符串值。问题是,我不希望一个人在这个问题中输入一个整数,所以我检查一行是否有整数。
#include "stdafx.h"
#include "stdio.h"
#include <iostream>
#include <ctime>
#include <string>
#include <time.h>
#include <algorithm>
#include "ThreeWayRace.h"
#include <cctype>
#include <functional>
using namespace std;
void Options()
{
string carColor;
int carNumber;
int s;
cout << "Please type a color in for your car: ";
cin>>carColor;
bool contains_non_alpha
= std::find_if(carColor.begin(), carColor.end(),
std::not1(std::ptr_fun((int(*)(int))std::isalpha))) != carColor.end();
while (contains_non_alpha == true)
{
cout << "Please enter letters only. ";
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cin>>carColor;
}
答案 0 :(得分:2)
正如评论中所说,你实际上并没有在循环中进行检查,这意味着contains_non_alpha
的值永远不会改变。
简单的解决方案是将检查本身作为循环条件的一部分,不需要临时变量。
使用我的评论中的std::all_of
功能,您可以这样做。
while (!std::all_of(std::begin(carColor), std::end(carColor), std::isalpha))
{
...
}
你也可以像这样使用do while
循环
void Options()
{
std::string carColor;
do
{
std::cout << "Please type a color in for your car (letters only): ";
std::cin >> carColor;
} while (!std::all_of(...));
int carNumber;
// ... rest of code...
}