/* in this program, add input checking to make sure that the name, phone number,
ID: 3571264 • Letter: #
Question
/*
in this program, add input checking to make sure that the name, phone number, and age are actually entered.
Sample output:
Enter a name: (none entered)
Please enter a name: Ernst Bekkering
Enter a phone number: (none entered)
Please enter a phone number...
9184445678
Enter an age:
(none entered)
50
Info written to file...
Press any key to continue . . .
*/
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
struct Info
{
string name;
string phoneNumber;
int age;
};
void getInfo(Info&);
void outputInfo(Info);
int main()
{
Info person;
getInfo(person);
outputInfo(person);
return 0;
}
void getInfo(Info &s)
{
cout << "Enter a name: ";
getline(cin, s.name);
cout << "Enter a phone number: ";
getline(cin, s.phoneNumber);
cout << "Enter an age: ";
cin >> s.age;
}
void outputInfo(Info s)
{
fstream outFile;
outFile.open("InfoFile.txt", ios::out);
outFile << s.name << endl;
outFile << s.phoneNumber << endl;
outFile << s.age;
cout << " Info written to file... ";
outFile.close();
}
Explanation / Answer
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
struct Info
{
string name;
string phoneNumber;
int age;
};
void getInfo(Info&);
void outputInfo(Info);
int main()
{
Info person;
getInfo(person);
outputInfo(person);
return 0;
}
void getInfo(Info &s)
{
cout << "Enter a name: ";
getline(cin, s.name);
/* if nothing has been entered by the user */
if(s.name.empty()){
do{
cout << "Please enter a name: ";
getline(cin, s.name);
}while(s.name.empty());
}
/* if nothing has been entered by the user */
cout << "Enter a phone number: ";
getline(cin, s.phoneNumber);
if(s.phoneNumber.empty()){
do{
cout <<"Please enter a phone number... ";
getline(cin, s.phoneNumber);
}while(s.phoneNumber.empty());
}
cout << "Enter an age: ";
cin>>s.age;
/* if nothing has been entered by the user */
if(cin.fail()){
do{
cin>>s.age;
}while(cin.fail());
}
}
void outputInfo(Info s)
{
fstream outFile;
outFile.open("InfoFile.txt", ios::out);
outFile << s.name << endl;
outFile << s.phoneNumber << endl;
outFile << s.age;
cout << " Info written to file... ";
outFile.close();
}
/****OUTPUT***********
Enter a name:
Please enter a name:
Please enter a name: skskks
Enter a phone number:
Please enter a phone number... 81191919
Enter an age:
67
Info written to file...
**********OUTPUT***********/
/* Note: This code has been tested on g++ compiler,Please ask in case of any doubt,would glad to help!! */
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.