c++ prevent to input not integer - c++

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!

Related

working on array of strings assignment and got stuck on this error "no match for "operator<<"

#include <iostream>
#include <cstring>
using namespace std;
char name[30];
char answer[10];
char KeytoCorrection [10][6]={"TRUE","FALSE","TRUE","FALSE","FALSE","FALSE","TRUE","TRUE","TRUE","FALSE"};
char remarks [2][7]= {"PASSED", "FAILED"};
int x,y, score=0;
int main()
{
cout<<"Name: ";
cin.getline(name,30);
cout<<endl;
cout<<"ANSWERS: "<<endl;
for(x=0;x<=9;x++)
{
cout<<" "<<x+1<<". ";
cin<<(answer [x] ,6);
}
for(x=0;x<=9;x++)
{
y=strcmpi(answer[x],KeytoCorrection[x]);
if (y==0)
{
score++;
}
if (score>=6)
{
strcpy(score,remarks[0]);
}
else
{
strcpy(score,remarks[1]);
}
cout<<"-------------------------"<<endl;
cout<<"SCORE : ";
cout<<"REMARKS :";
return 0;
}
Im new to C++ and this is my assignment in array of strings, I cant really figure out what's wrong with my code. the error "no match for 'operator<<' always appear and I dont know how to solve it.
any help will be appreciated. thank you.
You will need to do a couple of things. First of all you need to change how your anwsers variable is declared, so you should change:
char answer[10];
to
char answer[10][6];
This is because you have made only one dimensional array of characters meaning you can hold 10 differenct chars. But the inputs are either TRUE or FALSE so you need two dimensions.
Then you just need to change how you read the inputs from
cin<<(answer[x] ,6);
to
cin.getline(answer[x], 6);
This should resolve your issues with reading and checking inputs.
Here is your complete corrected code:-
#include <iostream>
#include <cstring>
#include<string>
using namespace std;
char name[30];
char answer[10][6];
char KeytoCorrection [10][6]={"TRUE","FALSE","TRUE","FALSE","FALSE","FALSE","TRUE","TRUE","TRUE","FALSE"};
string remark;//change1
int x,y, score=0;
int main()
{
cout<<"Name: ";
cin.getline(name,30);
cout<<endl;
cout<<"ANSWERS: "<<endl;
for(x=0;x<=9;x++)
{
cout<<" "<<x+1<<". ";
cin.getline(answer [x] ,6);
}
for(x=0;x<=9;x++)
{
y=strcmpi(answer[x],KeytoCorrection[x]);
if (y==0)
{
score++;
}
}
if (score>=6)
{
remark="PASSED";//change2
}
else
{
remark="FAILED";//change2
}
cout<<"-------------------------"<<endl;
cout<<"SCORE : "<<score<<"\n";//change3
cout<<"REMARKS :"<<remark<<"\n";//change3
return 0;
}
You may ask if any doubt.

Problem with read and write functions in c++ [duplicate]

First time execution is success without any error but when it creates Data.bin I get some error when I use fread.
Sorry I don't know how to ask it so please look at the program.
I commented the error making statement.
#include<iostream>
#include<vector>
using namespace std;
typedef struct myStuff
{
int cdno;
string content,des;
}MS;
int main()
{
vector<MS> data;
int i=0;
string in;
FILE *fr=NULL,*fw=NULL;
fr=fopen("Data.bin","rb");
//----------------------------------------------------------------------
if(fr!=NULL)
{
do
{
data.resize(++i);
}while( fread(&data[i-1],sizeof(MS),1,fr) ); //ERROR
fclose(fr);
}
else
data.resize(++i);
//----------------------------------------------------------------------
while(1)
{
cout<<"Enter x to exit or c to continue updating data: ";
cin>>in;
if(in=="x"||in=="X")
{
fw=fopen("Data.bin","wb");
fwrite(&data[i],sizeof(MS),i,fw);
fclose(fw);
exit(0);
}
else if(in=="c"||in=="C")
{
cout<<"Enter CD no: ";
cin>>data[i-1].cdno;
cout<<"Enter Contents: ";
cin>>data[i-1].content;
cout<<"Enter Description: ";
cin>>data[i-1].des;
data.resize(++i);
}
else
cout<<"Try Again..."<<endl;
}
}
you shouldn't use sizeof(string) or sizeof a structure that contains a string, that's meaningless, it just gives you the compile time (static) size of the class string. you should instead use string.size() which returns the dynamic size of the string.

C++ How to only accept a char input and make the program exit if user inputs string or int etc

Hey guys so I'm writing a program where I can only in one letter(ex. a,b,c) and I want the program to exit if the user tries to enter anything else ex)string int etc. The code sample I have so far is this. When I try to run this it the program will always say that the input is a letter.
#include <iostream>
using namespace std;
int main(){
char guess;
bool isnotletter
cout<<"Enter your guess"<<endl;
cin>>guess;
isnotletter=cin.fail();//cin.fail returns true if the input is something that disagrees with the data type (ex string and int would)
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
if(isnotletter==true)
{
cout<<"Error"<<endl;
exit(1);
}
else
cout<<"You are a letter"<<endl;
}
A simple way to do this, including flushing the line in case of bad input, would be to read the whole line and see if it consisted of a single character:
std::string s;
if ( !getline( cin, s ) ) // reads a whole line
cout << "Error or end-of-file\n";
else if ( s.size() != 1 )
cout << "Input was not a single character\n";
else if ( !isalpha(s[0], locale()) )
cout << "Input was not a letter\n";
else
cout<<"You are a letter"<<endl;
Of course, you could combine some of those error conditions if you are not interested in specific error messages.
I think isalpha() function helps you.
Source
#include <iostream>
#include <ctype.h>
#include <string.h>
using namespace std;
int main(){
string guess;
cout<<"Enter your guess"<<endl;
cin>>guess;
if( (!isalpha(guess[0])) || (guess.size() > 1) )
{
cout<<"Error"<<endl;
return -1;
}
else
cout<<"You are a letter"<<endl;
return 0;
}
cin.fail() will return true if there is an exception thrown when assigning a value, that much is correct. However, using cin to receive a string and assign it to a character doesn't throw an exception, as what happens is that cin simply takes the first character in the input buffer and assigns it to guess, leaving the rest of the string in queue within the input buffer. This is considered acceptable by cin.
In your code, if the user had written "hello", guesswill have the character h. If you use another cin below, and assign it to let's say char mychar, it won't ask the user again, as there is still input waiting. Instead, it'll assign the next character e to mychar.
Example:
#include <iostream>
using namespace std;
int main(){
char guess;
char mychar;
bool isnotletter;
cout<<"Enter your guess"<<endl;
cin>>guess;
isnotletter=cin.fail();
//cin.fail returns true if the input is something that disagrees with the data type (ex string and int would)
cin>>mychar;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
if(isnotletter==true)
{
cout<<"Error"<<endl;
exit(1);
}
else
cout<<"You are a letter"<<endl;
system("pause");
return 0;
}
The second char mychar will receive the second character in the first string input, without asking for the user to input again.
A solution could be using a string to get all the inputs, and if you want then you can assign the first letter of the string to your char. Later, you can use if and measure the string size, and if it is >1 then output the Error message.
#include <iostream>
#include <string>
using namespace std;
int main(){
string myString;
char mychar;
cout<<"Enter your guess"<<endl;
cin >> myString;
mychar = myString[0];
cin.ignore(numeric_limits<streamsize>::max(),'\n');
if(myString.size() > 1)
{
cout<<"Error"<<endl;
//exit(1);
}
//Code to check for numbers
else if(string::npos != myString.find_first_of("0123456789"))
{
cout << "digit(s)found!" << std::endl;
}
else
cout<<"You are a letter"<<endl;
system("pause");
return 0;
}
For text validation, regex is quiet of a powerful tool in general (can be slow though).
regex charRegex("(\\+|-)?[[:alpha:]]+");
string input;
cout<<"Input : "<<endl;
cin>>input;
if(!regex_match(input,charRegex))
cout<<"Invalid input"<<endl;
Companion of every regex fanatic.

C++ encrypt and decrypt secret messages using files

I have my prototypes in a header file, but I need some help. I am having some trouble getting the program to compile all the way through. It appears to be getting caught in a loop with the input. Possibly some issues with the functions. Thanks in advance for any input.
#include <iostream>
#include <conio.h>
#include "header.h"
#include <fstream>
class Caesar
{
public: void readText(char *input);
void encrypt(char *input,char *output,char *key);
void decrypt(char *input,char *output,char *key);
};
void main()
{
Caesar a;
char key[1000];
ifstream fin;
int choice;
char input[100],output[100];
cout<<"\n Enter input file: ";
cin>>input;
cout << input;
cout<<"\n Enter output file: ";
cin>>output;
cout <<output;
cout<<"\n Enter key: ";
cin>>key;
cout <<key;
cout<<"\n\n 1. Encrypt\n 2. Decrypt\n\n Select choice(1 or 2): "<< endl;
cin >> choice;
cout << choice;
a.readText(input);
if(choice==1)
{
a.encrypt(input,output,key);
}
if(choice==2)
{
a.decrypt(input,output,key);
}
else
{
cout<<"\n\n Unknown choice";
}
}
void Caesar::readText(char *input)
{
ifstream reader;
char buf;
reader.open(input);
cout<<"\n\n <--- "<<input<<" --->\n";
buf=reader.get();
while(!reader.eof())
{
cout<<buf;
buf=reader.get();
}
reader.close();
}
void Caesar::encrypt(char *input,char *output,char *key)
{
ifstream reader;
ofstream writer;
char buf;
reader.open(input);
writer.open(output);
buf=reader.get();
while(!reader.eof())
{
if(buf>='a'&&buf<='z')
{
buf-='a';
buf+=key[buf];
buf%=26;
buf+='A';
}
writer.put(buf);
buf=reader.get();
}
reader.close();
writer.close();
readText(input);
readText(output);
}
void Caesar::decrypt(char *input,char *output,char *key)
{
ifstream reader;
ofstream writer;
char buf;
reader.open(input);
writer.open(output);
buf=reader.get();
while(!reader.eof())
{
if(buf>='A'&&buf<='Z')
{
buf-='A';
buf+=26-key[buf];
buf%=26;
buf+='a';
}
writer.put(buf);
buf=reader.get();
}
reader.close();
writer.close();
readText(input);
readText(output);
}
if(choice=1)
should be
if(choice==1)
and also in the other if
In your case, you are assigning the value 1 to choice, then test if choice is true, and it is, since any non-zero numeral type is implicitly casted to bool true.
I have just executed your code and tried debugging it and took a screen shot
you program gets into a loop after entering the choice.there is no problem with cin>>.
From your comments, it seems like you're just trying to debug main. Everything seems to work fine. What are you inputting for key? If it's a very large integer, that may be your problem as it might exceed the maximum integer range and cause overflow.
Your key is an integer variable. You are inputting a string for the file name that holds your key, so that should be changed to a C string array. Change all of the passed key parameters to char* instead of int.
You have an infinite loop when the readText() function is called.
Maybe try this:
void Caesar::readText(char *input)
{
ifstream reader(input);
if(reader.is_open())
{
char buf;
cout<<"\n\n <--- "<<input<<" --->\n";
while(reader.get(buf))
{
cout << buf;
}
}
reader.close();
}
Make sure that your text file is in the same folder as your code. See this for more details: ifstream not opening file

How do I compare a string variable to an array of strings created from a file

Hello Ive been working on a program where I have a file with 3 columns containing both the inauguration year and departure year of a president, along with the name of the president. Im trying to have the user input a president and have the program return the start and stop year. I began by opening the file (which opens correctly) and making 3 arrays, 2 integer arrays and one string array. The program runs but when I press 2 regardless of what name I enter the bool stays false. The file can be found here: http://pastebin.com/8h3BJxGD
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
char junk, x;
int start[100],stop[100],year,i,count=0;
string names[100],president;
ifstream file;
file.open("presidents.txt");
if(file.fail())
cout<<"failed to open file"<<endl;
for(i=0;file>>start[i];i++)
{
file>>stop[i];
file.get(junk);
getline(file,names[i]);
cout<<start[i]<<stop[i]<<names[i]<<endl;
count++;
}
do
{
cout<<"What would you like to know?"<<endl;
cout<<"Press 1 for who was President in what year"<<endl;
cout<<"Press 2 for the years served by a President"<<endl;
cout<<"Press 3 to stop"<<endl;
cin>>x;
if(x=='1')
{
bool valid=false;
cout<<"Enter a year: "<<endl;
cin>>year;
for(i=0;i<count;i++)
{
if(start[i]<=year&&stop[i]>=year)
{
cout<<names[i]<<endl;
cout<<endl;
valid=true;
}
}
if(valid==false)
{
cout<<"Invalid year"<<endl;
cout<<endl;
}
}
if(x=='2')
{
bool valid=false;
cout<<"Enter a President: "<<endl;
cin>>president;
getline(cin,president);
for(i=0;i<count;i++)
{
if(president==names[i])
{
cout<<start[i]<<"-"<<stop[i]<<endl;
cout<<endl;
valid=true;
}
}
if(valid==false)
{
cout<<"Please be more percise"<<endl;
cout<<endl;
}
}
}
while (x!='3');
cin>>junk;
return 0;
}
Here, problem is not with the comparison, but with input string into president variable, try printing president variables value, you will understand the problem.
You need to add following line after reading x.
cin.ignore(); //add this line after cin>>x;
This will remove \n from the input buffer and will not cause any issue while reading president string. You need to take care of such issues while combining use of formatted input (i.e. >>) with unformatted input (i.e. get(), getline() etc).
Below is the modified code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
char junk, x;
int start[100],stop[100],year,i,count=0;
string names[100],president;
ifstream file;
file.open("president.txt");
if(file.fail())
cout<<"failed to open file"<<endl;
for(i=0;file>>start[i];i++)
{
file>>stop[i];
file.get(junk);
getline(file,names[i]);
cout<<start[i]<<stop[i]<<names[i]<<endl;
count++;
}
do
{
cout<<"What would you like to know?"<<endl;
cout<<"Press 1 for who was President in what year"<<endl;
cout<<"Press 2 for the years served by a President"<<endl;
cout<<"Press 3 to stop"<<endl;
cin>>x;
cin.ignore();
if(x=='1')
{
bool valid=false;
cout<<"Enter a year: "<<endl;
cin>>year;
for(i=0;i<count;i++)
{
if(start[i]<=year&&stop[i]>=year)
{
cout<<names[i]<<endl;
cout<<endl;
valid=true;
}
}
if(valid==false)
{
cout<<"Invalid year"<<endl;
cout<<endl;
}
}
if(x=='2')
{
bool valid=false;
cout<<"Enter a President: ";
getline(cin,president);
for(i=0;i<count;i++)
{
if(president==names[i])
{
cout<<start[i]<<"-"<<stop[i]<<endl;
cout<<endl;
valid=true;
}
}
if(valid==false)
{
cout<<"Please be more percise"<<endl;
cout<<endl;
}
}
}
while (x!='3');
cin>>junk;
return 0;
}
Following is the output:
What would you like to know?
Press 1 for who was President in what year
Press 2 for the years served by a President
Press 3 to stop
2
Enter a President: Theodore Roosevelt
1901-1909
if(president==)
if president == what???
Also,
getline(cin,president); //why this line?
if you have already read the file and put into data structure, then just search through the data structure for the name of the president that the user enters...if you find it, keep track of the index as you have done and print out the start[] and stop[] at the same index...