gpt4 book ai didi

c++ - 验证无效字符的字符串

转载 作者:太空狗 更新时间:2023-10-29 21:21:51 26 4
gpt4 key购买 nike

我今天正在研究如何验证字符串输入是否包含无效字符(例如数字),不幸的是没有成功。我正在尝试验证字符串以获取客户姓名,并检查是否有任何数字。

#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'));

该函数似乎可以很好地完成工作,但仅限于第一个输入。例如,当我运行程序并输入数字 3 时,将显示一条错误消息并要求用户再次输入姓名。用户输入有效名称后,即使没有使用数字或特殊字符,程序也会不断要求新输入并显示相同的错误消息。

最佳答案

我已经稍微更改了你的代码,但是因为已经很晚了,我明天还要去上大学,所以我会把它留给你看看我做了什么:

#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'));
}

关于c++ - 验证无效字符的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21711629/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com