In my code, I want to prevent the user input not integer words. my code is bottom.
#include<iostream>
#include<fstream>
#include<string>
#include<boost/regex.hpp>
#include<iomanip>
using namespace boost;
using namespace std;
int main()
{
int number;
string name,Telephone,email;
ofstream myoutfile("directory.txt");
ifstream myinfile;
bool isvalid=false;
char a[256];
char b[256];
regex reg_email("^\\w+([\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,3})+$");
regex reg_tel("^\\(?(\\d{3})\\)?-?(\\d{3})-(\\d{4})$");
while(number!=3)
{
cout<<"(1)Add a new record"<<endl;
cout<<"(2)Display the entire database"<<endl;
cout<<"(3)Exit"<<endl;
cin>>number;
if(number==1)
{
cout<<"enter your name."<<endl;
cin>>name;
cout<<"enter your email."<<endl;
cin.ignore(INT_MAX,'\n');
cin.getline(b,256);
while (regex_match(b,reg_email)==0)
{
cout<<"data wrong!!!!!!"<<endl;
cin.getline(b,256);
}
cout<<"enter your telephone numbers. EX:012-111-1111"<<endl;
cin.ignore(INT_MAX,'\n');
cin.getline(a,256);
while(regex_match(a,reg_tel)==0)
{
cout<<"data wrong!";
cin.getline(a,256);
}
myoutfile<<setiosflags(ios::left)<<setw(30)<<name<<setiosflags(ios::left)
<<setw(30)<<b<<setiosflags(ios::left)<<setw(30)<<a<<endl;
}
else if(number==2)
{
myinfile.open("directory.txt",ios::in);
string temp;
cout<<setiosflags(ios::left)<<setw(30)<<"name";
cout<<setiosflags(ios::left)<<setw(30)<<"email";
cout<<setiosflags(ios::left)<<setw(30)<<"telephone"<<endl;
while(!myinfile.eof())
{
getline(myinfile, temp);
cout<<temp<<endl;
}
myinfile.close();
}
else if(number==3)
{
cout<<"BYE!";
}
else if(scanf("%d",&number)!=1)
{
cout<<"Enter number!!!";
break;
}
}
return 0;
}
I have some question in the code.
First,
It will be fine when while loop run the first time,
but when the loop run the second time, I input an non-integer, it will show messy code.
Does anyone know?
Second,
cout<<"enter your telephone numbers. EX:012-111-1111"<<endl;
cin.ignore(INT_MAX,'\n');
cin.getline(a,256);
while(regex_match(a,reg_tel)==0)
{
cout<<"data wrong!";
cin.getline(a,256);
}
in above code, even if I type the correct format of the telephone number,
it always show me the "data wrong!" message, but I type it again, the regex_match test will be fine.
above is my question, sincerely thanks!