C++ 验证无效字符的字符串
我今天做了一些研究,研究如何验证字符串输入中的无效字符,例如数字,不幸的是没有成功。我正在尝试验证获取客户名称的字符串,并检查是否有任何数字C++ 验证无效字符的字符串,c++,string,function,validation,input,C++,String,Function,Validation,Input,我今天做了一些研究,研究如何验证字符串输入中的无效字符,例如数字,不幸的是没有成功。我正在尝试验证获取客户名称的字符串,并检查是否有任何数字 #include "stdafx.h" #include <string> #include <iostream> #include <conio.h> #include <algorithm&g
#include "stdafx.h"
#include <string>
#include <iostream>
#include <conio.h>
#include <algorithm>
#include <cctype>
using namespace std;
string validateName(string name[], int i)
{
while(find_if(name[i].begin(), name[i].end(), std::isdigit) != name[i].end()){
cout << "No digits are allowed in name." << endl;
cout << "Please re-enter customer's name:" << endl;
cin.clear();
cin.ignore(20, '\n');
}
return name[i];
}
int main()
{
string name[10];
int i=0;
char newentry='n';
do{
cout << "Plase enter customer's name: " << endl;
getline(cin, name[i]);
name[i]=validateName(name, i);
i++
cout << "Would you like to enter another questionare? Enter either 'y' or 'n': " << endl;
cin >> newentry;
} while((newentry =='y') || (newentry=='Y'));
#包括“stdafx.h”
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
字符串验证名称(字符串名称[],int i)
{
while(find_if(name[i].begin(),name[i].end(),std::isdigit)!=name[i].end(){
cout如果名称不正确且包含数字,则函数validateName不会从循环中退出
我想您忘记在这个循环中放置getline
,以重新输入名称
还插入语句
cin.ignore(20, '\n');
cin >> newentry;
以前
getline(cin, name[i]);
在do-while循环中
或者更好地使用
cin.ignore( std::numeric_limits<std::streamsize>::max() );
它将新行字符放入输入缓冲区,下一个getline不读取任何内容。我对您的代码做了一些更改,但是已经很晚了,明天我必须去上大学,我将让您看看我做了什么:
#include <string>
#include <iostream>
#include <conio.h>
#include <algorithm>
#include <cctype>
using namespace std;
void validateName(string &name) //Pass by reference and edit given string not a copy, so there is no need to return it
{
cout << "Plase enter customer's name: " << endl;
cin.clear();
cin.sync();
getline(cin, name);
while (name.find_first_of("0123456789") != -1)
{
cout << "No digits are allowed in name." << endl;
cout << "Please re-enter customer's name:" << endl;
cin.clear();
cin.sync();
getline(cin, name);
}
}
int main()
{
string name[10];
int i = 0;
char newentry = 'n';
do{
validateName(name[i++]);
if (i >= 10)
break;
cout << "Would you like to enter another questionare? Enter either 'y' or 'n': " << endl;
do{
cin.clear();
cin.sync();
cin >> newentry;
} while ((newentry != 'y') && (newentry != 'Y') && (newentry != 'n') && (newentry != 'N'));
} while ((newentry == 'y') || (newentry == 'Y'));
}
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
void validateName(string&name)//按引用传递并编辑给定的字符串,而不是副本,因此无需返回该字符串
{
不能脱离主题。y将字符串数组传递给fn?只传递字符串。如果可以使用std::vector
,为什么要使用数组?如果我不传递字符串数组,否则它将不起作用。vector?我以前从未使用过这些。我仍然是一个noob。如果我认为我正确地跟踪了你,在得到有效的n之前,你不应该递增I
名称。您的名称无效,但您仍可以继续获取下一个名称。没有区别:(@noobuser333)您的函数有无限循环,因为如果名称不正确,函数将无法退出。当然,如果名称不正确,我希望用户输入一个新的有效名称。只有在名称有效时,它才应返回int main并跟随程序的其余部分。