我刚刚完成(非常成功)介绍计算机科学I和II在一个领先的NCAA Division 1大学专门用C ++教授,我不能告诉你我多少次搜索这个网站如何接受和验证int和只有一个int,一个char,只有一个char,一个字符串,只有一个字符串?毫无疑问,这些问题有很多种方法,但通常SO上的内容对特定情况非常具体。我正在寻找一种符合上述要求的通用方法。我提供我的方法,我自己制定了。我无法想象没有其他类似的地方做过或确实有同样的问题。如果还有其他方法可以完成这些看起来很小的任务a。)工作,以及b)涉及的编码少于我的概述,我有兴趣看到它。
答案 0 :(得分:0)
#include <string>
#include<iostream>
using std::cin;
using std::cout;
int main() {
int answer1 = 0;
cout << "An int Question?\n"
<< "1. Yes.\n"
<< "2. No.\n";
while (!(cin >> answer1) || answer1 < 1 || answer1 > 2) {
cin.clear();
cin.ignore(std::numeric_limits<std::stream_size>::max(), '\n');
cout << "Input Error!\n"
<< "An int Question?\n"
<< "1. Yes.\n"
<< "2. No!\n";
}
cout << "The int answer is " << answer1 << "\n\n";
char answer2 = 'X';
cout << "A char Question?\n"
<< "A. Yes.\n"
<< "B. No.\n";
while (!(cin >> answer2) || !isalpha(answer2) || answer2 != 'A' && answer2 != 'B') {
cin.clear();
cin.ignore(std::numeric_limits<std::stream_size>::max(), '\n');
cout << "Input Error!\n"
<< "A char Question?\n"
<< "A. Yes.\n"
<< "B. No!\n";
}
cout << "The char answer is " << answer2 << "\n\n";
std::string answer3 = "";
cout << "A string Question?\n"
<< "Yes.\n"
<< "No.\n";
while (!(cin >> answer3) || answer3 != "Yes" && answer3 != "No") {
cin.clear();
cin.ignore(std::numeric_limits<std::stream_size>::max(), '\n');
cout << "Input Error!\n"
<< "A string Question?\n"
<< "Yes.\n"
<< "No.\n";
}
cout << "The string answer is " << answer3 << "\n\n";
}