How to fix this string validation (Telephone directory system) - c++

Im talking about the string validation in void enter() , what im trying to do is create a system , where if someone accidentally puts a number in Enter name field , they need to write it again
im just not being able to solve this string validation at all.
I tried something like
after cout<<"Enter name";
for(int i=0;i<strlen(name);i++)
{
gets(name);
if(isalpha(name[i]))
cout<<"There is a number in the input , try again";
}
include<fstream.h>
include<stdio.h>
include<conio.h>
include<string.h>
include<stdlib.h>
class Directory
{
char name[20];
char num[30];
char address[50];
public:
void enter()
{
cout<<"Enter name: "<<endl;
gets(name);
cout<<"Enter number: "<<endl;
gets(num);
cout<<"Enter address: "<<endl;
gets(address);
}
it did work , but if I enter a name "mar3", now i have to enter Mark four times for it to take the record.

I think this is what you want to do. You want to reenter the name untill it meets your requrement.
bool validate(char name[])
{
for(int i=0;i<strlen(name);i++)
if(isalpha((unsigned char)name[i]))
{
cout<<"There is a number in the input , try again";
return 0;
}
return 1;
}
and while reading name do this.
gets(name);
while(!validate(name))
{
gets(name);
}
UPD :
use string and getline to read.
#include<fstream>
#include<cstdio>
#include<cstring>
#include<stdlib.h>
#include<stdio.h>
#include<iostream>
using namespace std;
bool validate(string name)
{
for(int i=0;i<name.length();i++)
if(isalpha(name[i]))
{
cout<<"There is a number in the input , try again\n";
return 0;
}
return 1;
}
class Directory
{
string name,num,address;
public:
void enter()
{
cout<<"Enter name: "<<endl;
getline(cin,name);
while(!validate(name))
{
getline(cin,name);
}
cout<<"Enter number: "<<endl;
getline(cin,num);
cout<<"Enter address: "<<endl;
getline(cin,address);
}
};
here is you want to also limit the length of the name or number you can make another validator for that

Related

Build giving 1d returned 1 exit status

Unable to build a single C++ file in Geany.
A program to show the employee details. When I clicked compile, it shows compilation successful. But when I build it, it shows this. Can't execute too.
#include<iostream>
#include<conio.h>
using namespace std;
class employee
{
public:
int id,age;
char name[25];
float salary;
void getdata()
{
cout<<"\n enter employee id";
cin>>id;
cout<<"enter emplyee name";
cin>>name;
cout<<"\n enter employee age";
cin>>age;
cout<<"\n enter emplyee salary";
cin>>salary;
}
void putdata()
{
cout<<"\n id="<<id<<"\n name="<<name<<"\n age="<<age<<"n salary="<<salary;
}
void main()
{
int i;
employee e[2];
for(i=0;i<2;i++)
{
cout<<"\n enter details of"<<i+1<<"employee";
e[i].getdata();
}
cout<<"\n details of employees";
for(i=0;i<2;i++)
{
e[i].putdata();
}
getch();
}
};
Error Code:

How to ofstream and then ifstream a 2D string array in same program in c++. Here is the code which I wrote. I am a starter

#include <iostream>
#include<fstream>
using namespace std;
int main()
{
int a;
cout<<"enter key ";
cin>>a;
if(a==1)
{
string info[0][1];
cout<<"enter your name ";
getline(cin, info[0][0]);
cout<<"enter father's ";
getline(cin, info[0][1]);
ofstream file("info.txt");
for(int i=0;i<=1;i++)
{
file<<info[0][i]<<" ";
}
file.close();
}
int b;
cout<<"enter b ";
cin>>b;
if(b==2)
{
char info[0][1];
ifstream file("info.txt");
for(int j=0;j<=1;j++)
{
file>>info[0][j];
}
cout<<endl;
for(int i=0;i<=4;i++)
{
cout<<info[0][i]<<" ";
}
}
return 0;
}
I want to store user and his father's name (other info as well which is not mentioned in code) in the form of 2d array, and ofstream that array and later ifstream the same.
in the code:
After taking input a=1, it displays "enter your name", to which it is not taking any input i.e nothing gets typed in the output window from keyboard. (no compiler error) Please help!!
I am coding in code blocks.
This is not legal C++ (because arrays of size zero are not legal).
string info[0][1];
cout<<"enter your name ";
getline(cin, info[0][0]);
cout<<"enter father's ";
getline(cin, info[0][1]);
ofstream file("info.txt");
for(int i=0;i<=1;i++)
{
file<<info[0][i]<<" ";
}
All you need is two strings, so just
string info[2];
cout<<"enter your name ";
getline(cin, info[0]);
cout<<"enter father's ";
getline(cin, info[1]);
ofstream file("info.txt");
for(int i=0;i<2;i++)
{
file<<info[i]<<" ";
}
Thne when you try to read them back, you've made the same error, and added a new one
char info[0][1];
Why did you switch to char here? Again you need two strings.
string info[2];
Finally for some reason at the end you are trying to output five strings.
for(int i=0;i<=4;i++)
{
cout<<info[0][i]<<" ";
}
Again two is the magic number
for(int i=0;i<2;i++)
{
cout<<info[i]<<" ";
}
Plus you have the problem mentioned by Yksisarvinen. You need to fix that in the way mentioned in the link.

I am not able to get input after a certain point ( from the user) even though no error pops wile compiling [duplicate]

This question already has an answer here:
How to make cin work after using getline?
(1 answer)
Closed 3 years ago.
This program is a small hospital management program.
It works with C++ and uses binary files and classes.
it is a simple prog that taken the input of patients details and saves in a binary file, and displays the patients details by searching regno.
The code does not run beyond : cin>>A1.PI.age; and starts printing endless loop of something.
PLEASE REPLY ME ON WHERE HAVE I GONE WRONG
here is the code:
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include<string.h>
#include<stdlib.h>
class all
{ private:
struct address
{ int house;
char street[30];
char city[30];};
struct patient_info
{ char name[40];
address AD1;
int age;
int maritalstatus;
int regno;
char bldgrp[3];
char sex;
}PI;
int task;
protected:
void firstpinfo();
void showpinfo();
void enterpinfo();
public:
void tasks();
char ch;
int serial;
}A1;
class date :public all
{ private :
int day;
int month;
int year;
public:
void enterdate()
{cout<<"enter day of date";
cin>>day;
cout<<"enter month";
cin>>month;
cout<<"enter year";
cin>>year;
}
void showdate()
{ cout<<day<<"/"<<month<<"/"<<year;}
}D1;
//global variables
int count,attempt;
void main()
{ count=0;
cout<<" HOSPITAL MANAGEMENT SOFTWARE
";
D1.enterdate();
A1.tasks();
getch();
while(count==0)
{ A1.tasks();
cout<<"press 0 to continue and 1 to exit";
cin>> count;
}
getch();
}
void all::tasks()
{ attempt=0;
D1.showdate();
cout<<"select task"<<endl
<<"1.show patient details"<<endl
<<"2.enter details of a patient"<<endl
<<"3.exit prog"<<endl;
cin>>task;
switch(task)
{
case 1: {cout<<"enter regno to display"<<endl;
int search;
cin>>search;
fstream fon;
fon.open("hospital.dat",ios::in|ios::binary);
if(!fon)
{cout<<"error in opening"<<endl;
getch();
exit(0);
}
else
{fon.read((char*)&A1,sizeof(A1));
if(A1.PI.regno==search)
{cout<<"showing details";
A1.showpinfo();}
else
{cout<<"regno not found";}
fon.close();
}
break;}
case 2: {cout<<"adding a new patient";
A1.enterpinfo();
fstream fan;
fan.open("hospital.dat",ios::in|ios::binary);
if(fan)
{fan.write((char*)&A1,sizeof(A1));}
fan.close();
break;}
case 3: { cout<<"exiting...press any key";
getch();
exit(0);
break;
}
default: {cout<<"error... press anykey to try again";
getch();
A1.tasks();
};
}}//END OF TASKS
void all::showpinfo()
{cout<<"patient regno\n"<<A1.PI.regno<<endl;
cout<<"patient name\n"<<A1.PI.name<<endl;
cout<<"address of patient\n"<<A1.PI.AD1.house<<" "<< PI.AD1.street<<" "<<PI.AD1.city<<endl;
cout<<"blood group"<<A1.PI.bldgrp<<endl;
cout<<"sex"<<A1.PI.sex<<endl;
cout<<"data extracted";
}
void all:: enterpinfo()
{
cout<<"enter unique registration number";
cin>>PI.regno;
cout<<"enter patient name"<<endl;
cin.getline(A1.PI.name,50);
cout<<"enter address( house, street, city)"<<endl;
cin>>A1.PI.AD1.house;
cin.getline(A1.PI.AD1.street,30);
cin.getline(A1.PI.AD1.city,30);
cout<<"enter age in years"<<endl;
cin>>A1.PI.age;
cout<<"enter 1 for married and 0 for otherwise"<<endl;
cin>>A1.PI.maritalstatus;
cout<<"enter blood group"<<endl;
cin>>A1.PI.bldgrp;
cout<<"enter M for male and F for female";
cin>>A1.PI.sex;
}
why this happens :
This happens because you have mixed cin and cin.getline.
when you enter a value using cin, cin not only captures the value, it also captures the newline. So when we enter 2, cin actually gets the string ā€œ2\nā€. It then extracts the 2 to variable, leaving the newline stuck in the input stream. Then, when getline() goes to read the input, it sees ā€œ\nā€ is already in the stream, and figures we must have entered an empty string! Definitely not what was intended.
old solution :
A good rule of thumb is that after reading a value with cin, remove the newline from the stream. This can be done using the following :
std::cin.ignore(32767, '\n'); // ignore up to 32767 characters until a \n is removed
A better solution :
use this whenever you use std::getline() to read strings
std::getline(std::cin >> std::ws, input); // ignore any leading whitespace characters
std::ws is a input manipulator which tell std::getline() to ignore any leading whitespace characters
source : learncpp website
goto section (Use std::getline() to input text)
hope this is helpful
#include<iostream>
#include<fstream>
#include<string>
#include<cstdlib>
don't use .h extension
we don't think we need #include<conio.h> anymore
and isn't simpler
getline(cin, A1.PI.name) than cin.getline(A1.PI.name,50)
then resize its max size
A1.PI.name.resize(50);

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...

Problem in accepting a blank space to string in c++

I wrote this code to obtain name. telephone and address of a person and then i input these into class object variables:
#include<iostream>
#include<cstdlib>
#include<fstream>
#include<string>
using namespace std;
class contact{
public:
string name;//ALL CLASS VARIABLES ARE PUBLIC
unsigned int phonenumber;
string address;
contact(){//Constructor
name= "Noname";
phonenumber= 0;
address= "Noaddress";
}
/*void input_contact_name(string s){//function to take contact name
name=s;
}
void input_contact_number(int x){//function to take contact number
phonenumber=x;
}
void input_contact_address(string add){//function to take contact address
address=add;
}*/
};
int main(){
contact *d;
d= new contact[200];
string name,add;
int choice;//Variable for switch statement
unsigned int phno;
static int i=0;//i is declared as a static int variable
bool flag=false;
cout<<"\tWelcome to the phone Directory\n";//Welcome Message
cout<<"Select :\n1.Add New Contact\n2.Update Existing Contact\n3.Delete an Existing Entry\n4.Display All Contacts\n5.Search for a contact\n6.Exit PhoneBook\n\n\n";//Display all options
cin>>choice;//Input Choice from user
while(!flag){//While Loop Starts
switch(choice){//Switch Loop Starts
case 1:
cout<<"\nEnter The Name\n";
cin>>name;
d[i].name=name;
cout<<"\nEnter the Phone Number\n";
cin>>phno;
d[i].phonenumber=phno;
cout<<"\nEnter the address\n";
cin>>add;
d[i].address=add;
i++;
flag=true;
}
}
return 0;
}
However If I enter the name separated with its surname, the code bypasses the next cins and exits. Can some one help me out why this happens?
Same happens when I enter 10 digit cell no.
Thanks in advance
Use std::getline() instead of operator>> to extract a std::string containing whitespace.