I was doing some research today of how to validate a string input for invalid characters such as digits, unfortunately with no success. I am trying to validate string for getting customer's name, and check if there are any digits.
#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'));
The function seems to do the job fine, but only with the first input. For example when I run the program and enter a number 3, an error message will be displayed and user is asked to enter name again. After user enters a valid name, the program however keeps asking for a new input with the same error messages even if no digits or special characters are used.
I have changed your code a little, but as it is already very late and I have to go to university tomorrow, I'll leave it up to you to see what I did:
#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'));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With