如何验证字符串以确保不存在小于或等于1的非数字和整数



所以我目前正在用c++编写一个程序。我已经编写了以下函数。上面写着"//此处编码";这就是我的问题所在。基本上,该程序允许用户创建自己的测试txt文件。对于问题";这个测验应该有几个问题"用户将输入一个表示问题数量的数字。当必须验证用户输入时,就会出现问题。

有人能帮我创建一个执行以下操作的循环吗

  1. 确保用户只输入数字
  2. 确保输入的数字大于1
  3. 如果用户输入了非数字,则会给用户一条错误消息
  4. 如果用户输入的数字小于2,则会给用户一条错误消息
  5. 程序验证用户是否只按下回车键

一旦全部整理完毕,程序将在将NumberOfQuestions转换为int后将其设置为等于用户输入。

void WriteOutQuestions(string &QuizName)
{
ofstream WriteOut;
string filename = "";
string userInput = "";
int numberOfQuestions;
char userInputChar = '0';
bool IncludeCommments = false;
cout << "Name your filen";
getline(cin, filename);
cout << "Now give your new quiz a titlen";
getline(cin, QuizName);
cout << "How many questions should the quiz have?n";
getline(cin, userInput);
//code here
numberOfQuestions = stoi(userInput);
cout << "The quiz will contain " << numberOfQuestions << " questions." << endl;
cout<< "Would you like to include comments in any of the choices?n";
cout << "[Y/y for yes N/n for No]n";
getline(cin, userInput);
if (userInput == "y" && userInput == "Y")
IncludeCommments = true;
else
cout << "Comments disabled by user...n";
WriteOut.open(filename + ".txt");
if (!WriteOut)
{
cout << "The file was not found...n";
}
else
{
cout << "File was read!n";
}
WriteOut << QuizName << endl;
WriteOut << numberOfQuestions << endl;
for (int i = 0; i < numberOfQuestions; ++i)
{
cout << "What is question number " << i + 1 << "?n";
getline(cin, userInput);
WriteOut << "Q" << i + 1 << " " + userInput << endl;

cout << "What is choice A for question number " << i + 1 << "?n";
getline(cin, userInput);
WriteOut << "A) " + userInput << endl;

if (IncludeCommments == true)
{
cout << "What is the comment for choice A for question number " << i + 1 << "?n";
getline(cin, userInput);
WriteOut << userInput << endl;
}
else
WriteOut << "" << endl;

cout << "What is choice B for question number " << i + 1 << "?n";
getline(cin, userInput);
WriteOut << "B) " + userInput << endl;

if (IncludeCommments == true)
{
cout << "What is the comment for choice B for question number " << i + 1 << "?n";
getline(cin, userInput);
WriteOut << userInput << endl;
}
else
WriteOut << "" << endl;

cout << "What is choice C for question number " << i + 1 << "?n";
getline(cin, userInput);
WriteOut << "C) " + userInput << endl;

if (IncludeCommments == true)
{
cout << "What is the comment for choice C for question number " << i + 1 << "?n";
getline(cin, userInput);
WriteOut << userInput << endl;
}
else
WriteOut << "" << endl;

cout << "What is choice D for question number " << i + 1 << "?n";
getline(cin, userInput);
WriteOut << "D) " + userInput << endl;

if (IncludeCommments == true)
{
cout << "What is the comment for choice D for question number " << i + 1 << "?n";
getline(cin, userInput);
WriteOut << userInput << endl;
}
else
WriteOut << "" << endl;

cout << "Which choice is the right one? [A, B, C or D]n";
getline(cin, userInput);
while (userInput != "a" && userInput != "A" && userInput != "b" && userInput != "B" &&
userInput != "c" && userInput != "C" && userInput != "d" && userInput != "D")
{
cout << "Only A-D is acceptedn";
}
userInputChar = userInput[0];
if (userInputChar > 96)
{
userInputChar -= 32;
}
userInput = userInputChar;
cout << "userinput contains " << userInput << endl;
cout << "userinputchar contains " <<userInputChar << endl;
WriteOut << userInput << endl;
}
WriteOut.close();
}

首先,您需要更改&amp;在下面的代码到||运行代码的代码正确

if (userInput == "y" && userInput == "Y")
IncludeCommments = true;
else
cout << "Comments disabled by user...n";

在进行验证时,您可以在获取用户输入后维护一个标志变量

cout << "How many questions should the quiz have?n";
getline(cin, userInput);
int length=userInput.length(); //gives the length of string entered
int flag=0; //flag variable
for(int i=0;i<length;i++)
{
if((!(userinput[i]>='0'&&userinput[i]<=9))||isspace(s[i])) //i am 
considering space is not a problem
{
flag=1;
}
}
if(flag!=0)
{
cout<<"error:Non digit is entered"<<endl
}else
{
int numberofquestions = stoi(userinput);
if(numberofquestions<=1){
cout<<"error:number less than 2 is entered"<<endl;
}
}

选项太多,很难做出好的推荐。

我将向您展示几种解决方案。第一部分总是采用相同的方法:

  • 我们运行do循环
  • 首先,我们指导用户做什么
  • 然后我们读取输入
  • 然后我们,检查一下,如果都是数字
  • 如果我们有所有的数字,那么我们转换成一个数字
  • 如果数字大于1,则进行检查

如果我们发现错误,我们会再次循环。让我们看看下面代码中的选项

  1. 基于索引的循环和与字符数字的比较
  2. 基于索引的循环和isdigit函数的使用
  3. 基于范围的循环和isdigit函数的使用
  4. all_of算法及其isdigit函数的使用
  5. 正则表达式。还将处理空行
  6. 扩展正则表达式。也将处理空行,并且将检查数字>1

选项1-4需要额外检查空行。用户只需按回车键。

请参阅所有选项的代码:

#include <iostream>
#include <string>
#include <cctype>
#include <algorithm>
#include <regex>
int main() {
// We try to get input from the user and run a loop as long as it is not OK
bool inputIsOK{};
// This is the number of questions that we want to read
int numberOfQuestions{};
// Ask for valid input from user
do {
// Assume valid input
inputIsOK = true;
// Instruct user
std::cout << "nHow many questions should the quiz have? Enter a number > 1.n";
// Read complete line from the user
std::string line{};
if (std::getline(std::cin, line)) {
// Check, if all characters are valid (digits)
// Option 1 -------------------------------------------------------------------
// Index based for loop and compare with character digits
for (size_t i{}; i < line.length(); ++i) {
if (line[i] < '0' || line[i] > '9') {
inputIsOK = false;
std::cerr << "nError 1: Please enter digits onlyn";
break;
}
}
// Option 2 -------------------------------------------------------------------
// Index based for loop and use of isdigit function
for (size_t i{}; i < line.length(); ++i) {
if (not std::isdigit(line[i])) {
inputIsOK = false;
std::cerr << "nError 2: Please enter digits onlyn";
break;
}
}
// Option 3 -------------------------------------------------------------------
// Range based for loop and use of isdigit function
for (const char c : line) {
if (not std::isdigit(c)) {
inputIsOK = false;
std::cerr << "nError 3: Please enter digits onlyn";
break;
}
}
// Option 4 -------------------------------------------------------------------
// all_of algorithm and use of isdigit function
if (not std::all_of(line.begin(), line.end(), isdigit)) {
inputIsOK = false;
std::cerr << "nError 4: Please enter digits onlyn";
}
// Option 1-4 -----------------------------------------------------------------
// For option 1 to 4 you need to additionally check for empty line
if (inputIsOK && line.length() == 0) {
inputIsOK = false;
std::cerr << "nError 5: Please enter digits onlyn";
}
// Option 5 -------------------------------------------------------------------
// regex. Will also handle empty lines
if (not std::regex_match(line, std::regex("\d{1,6}"))) {
inputIsOK = false;
std::cerr << "nError 6: Please enter digits only (max 6)n";
}
// Option 6 -------------------------------------------------------------------
// Extened regex. Will also handle empty lines AND will check if number > 1
if (not std::regex_match(line, std::regex(R"([2-9]|([1-9][0-9]{1,6}))"))) {
inputIsOK = false;
std::cerr << "nError 7: Please enter number > 1  (Max 6 digits)n";
}
// End Option -----------------------------------------------------------------
// Check, if number is > 1
if (inputIsOK) {
numberOfQuestions = std::stoi(line);
if (numberOfQuestions < 2) {
inputIsOK = false;
std::cerr << "nError 8: Number too small. Enter number > 1n";
}
}
}
else {
std::cerr << "nError: General problem with inputn";
inputIsOK = false;
std::cin.clear();
}
} while (not inputIsOK);
return 0;
}

你可以选择你想要的任何选项。


然而。我不会使用上面的任何一个。

我会使用IOstream工具,直接读取一个无符号整数。如果输入错误,std::cin的状态将失败并指示问题。

所以,你可以用它来代替:

#include <iostream>
#include <limits>
int main() {
// We try to get input from the user and run a loop as long as it is not OK
bool inputIsOK{};
// This is the number of questions that we want to read
unsigned int numberOfQuestions{};
// Ask for valid input from user
do {
// Instruct user
std::cout << "nHow many questions should the quiz have? Enter a number > 1.n";
// Get input. Directly as number
inputIsOK = (std::cin >> numberOfQuestions) && (numberOfQuestions > 1);
// In case of error. Show message
if (not inputIsOK) {
std::cerr << "nError 1: Wrong inputn";
std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
}
} while (not inputIsOK);
return 0;
}

ignore函数将删除可能仍在输入缓冲区中的所有垃圾。

相关内容

  • 没有找到相关文章

最新更新