I am working on a simple demographics program. Enter the data and output it to a csv file. I am having issue validating data input for the name. Validation works fine if enter just number but if I enter an alphanumeric string twice it does not work. For example, if I type Max1, I get the exception, if I type Max1 again, it just moves on to the next function call. However if I enter just a string of digits it will not move on until I enter a correct alpha only string or two alphanumerics strings
#include <iostream>
#include <vector>
#include "People.h"
int main()
{
const short elements = 2;
PersonalData Demographics;
std::string input;
std::vector<std::string> response;
for (int i = 0; i < elements; i++)
{
std::cout << "Please enter first name of child: " << i+1 << std::endl;
std::cin >> input;
response.push_back(input)
Demographics.setName(response);
}
return 0;
}
People.hpp
#ifndef PEOPLE_H_INCLUDED
#define PEOPLE_H_INCLUDED
#include <vector>
class PersonalData
{
private:
std::vector<std::string> name;
public:
void setName(std::vector<std::string>&); //get the names of each person
};
#endif // PEOPLE_H_INCLUDED
People.cpp
#include <iostream>>
#include "People.h"
#include <vector>
void PersonalData::setName(std::vector<std::string> &names)
{
string retry;
bool valid=false; // we start by assuming that the entry is not valid
std::string::const_iterator it;
while(!valid) //start validation loop
{
for(int i=0; i <names.size(); i++)
{
for(it = names[i].begin(); it != names[i].end(); ++it) //start loop to check type of each char in string
{
if(isalpha(*it)) //if it is char set name to user names
{
name=names;
valid = true; //the entry was valid, jump out of loop
}
else //it was not just char, try again
{
std::cout << "Name should be alphabetic only. Try again: " <<endl;
std::cin >> retry;
names.erase(names.begin()+i); // remove the bad non-alphabetic entry from the names array
names.push_back(retry);
break;
}
}
}
}
}