C++ Contact File Program - c++

I have a question about my program that I am creating in C++ Visual Studios. First what I want to do is get all the Info about Accounts inputted from the user, then Displayed back to the user to make sure it was entered correctly. Then put that information into the file AccountInformation.txt. I have gotten it to all work up until now it's going from doing this fine cin >> Street then it will group the next two cin's together so I don't know why its doing that. here is the code and the sample output of the program as it runs now.
// CreateWriteDisplay.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <fstream>
#include <iostream>
#include <string>
#include <ostream>
using std::cout; //using namespace std is not a good practice **
using std::cin; //it's best to use std:: scope or using only what you need
using std::string; //not the whole namespace, C++17 allows for comma
using std::endl; //separated usings
using namespace std;
// Declares all the variables I need.
int AccountAge;
string LastName;
string FirstName;
string Ocupation;
string UserName;
string EmailAdd;
string HomeAddress;
string TeleNum;
string HomeDirectory;
string RoamingProfile;
string Street;
string City;
string State;
string Zipcode;
string YnRoaming;
//macro definitions for max variable length
#define MAX_NAME_LENGTH 50
#define MAX_ADDRESS_LENGTH 100
#define MAX_ABOUT_LENGTH 200
int main()
{
char name[MAX_NAME_LENGTH], address[MAX_ADDRESS_LENGTH],
about[MAX_ABOUT_LENGTH];
//Gets The Accounts Personal Information: Ocupation, Full Name, Age, Email, Home Address, Telephone Number, UserName, HomeDirectory, RoamingProfile,
cout << "Please enter your Ocupation: " << "\n";
getline(cin, Ocupation);
cout << "Enter Your First Name and Last name: " << "\n";
cin >> FirstName >> LastName;
cout << "Enter Your Age: " << "\n";
cin >> AccountAge;
cout << "Please enter your Email: " << "\n";
cin >> EmailAdd;
cout << "Please Enter Your Home Address( ex: 123(enter) Street( Enter), City Name(Enter), State(Enter), Zipcode(Enter)): " << "\n";
cin >> HomeAddress;
cout << "Enter Street Name" << "\n";
cout << "( ex: StreetName st " << "\n";
cin >> Street;
cout << "Enter City" << "\n" ;
cin >> City;
cout << "Enter State" << "\n";
cin >> State;
cout << "Enter Zipcode" << "\n";
cin >> Zipcode;
cout << "Please Enter Your Best Telephone Number(EX:508-675-4567): " << "\n";
cin >> TeleNum;
cout << "Please Enter Your UserName: " << "\n";
cin >> UserName;
cout << "Please Enter Your Account's HomeDirectory(EX:\\HOMEDIRECTORY\\): " << "\n";
cin >> HomeDirectory;
cout << "Do you have a Roaming Profile?(Y/N)" << "\n";
cin >> YnRoaming;
if (YnRoaming == "Y") {
cout << "Please Enter Your Roaming Profile Name(IF APPLYS): " << "\n";
cin >> RoamingProfile;
}
else {
string RoamingProfile = "N / A";
}
//getline(cin, HomeAddress);
// Displays All the information entered by the user To verify it was entered correctly.
cout << "Full Name: " << LastName << "," << FirstName << ", Length: " <<
FirstName.length() + LastName.length() << "\n" << "Age: " << AccountAge << "\n"
<< "Ocupation: " << Ocupation << "\n" << "UserName: " << UserName
<< "\n" << "Email Address: " << EmailAdd << "\n"
<< FirstName << "'s Home Address" << HomeAddress << Street << City << State << Zipcode
<< "\n" << " Primary Telephone Number: " << TeleNum << "\n" << UserName << "'s Home Directory: " << HomeDirectory
<< "\n" << UserName << "'s RoamingProfile: " << RoamingProfile << "\n";
// Create File and Write to it then Close it.
ofstream MyFile("AccountInformation.txt");
MyFile << "Full Name: " << LastName << "," << FirstName << ", Length: " << FirstName.length() + LastName.length() << "\n" << "Age: " << AccountAge << "\n"
<< "Occupation: " << Ocupation << ", Length: " << Ocupation.length() << "\n" << "UserName: " << UserName << "\n" << "Email Address: " << EmailAdd << "\n" << FirstName << "'s Home Address"
<< HomeAddress << "\n" << " Primary Telephone Number: " << TeleNum << "\n" << UserName << "'s Home Directory: " << HomeDirectory << "\n"
<< UserName << "'s RoamingProfile: " << RoamingProfile << "\n";
MyFile.close();
return 0;
}
Please enter your Ocupation:
Citizens For Citizens
Enter Your First Name and Last name:
Mark Monhan
Enter Your Age:
24
Please enter your Email:
mmonhan23#gmail.com
Please Enter Your Home Address( ex: 123(enter) Street( Enter), City Name(Enter), State(Enter), Zipcode(Enter)):
524
Enter Street Name
( ex: StreetName st
Street st
Enter City
Enter State
Boston MA
Enter Zipcode
Please Enter Your Best Telephone Number(EX:508-675-4567):
02726 603-854-7845
Please Enter Your UserName:
Please Enter Your Account's HomeDirectory(EX:\HOMEDIRECTORY\):
mgede
Do you have a Roaming Profile?(Y/N)
N
Full Name: Monhan,Mark, Length: 10
Age: 24
Ocupation: Citizens For Citizens
UserName: 603-854-7845
Email Address: mmonhan23#gmail.com
Mark's Home Address524StreetstBostonMA
Primary Telephone Number: 02726
603-854-7845's Home Directory: mgede
603-854-7845's RoamingProfile:
``` ***

You need to change the line right under the cin >> EmailAdd; to be cin.ignore(); then put getline(cin, HomeAddress); that will take the whole Address and store it all in the variable HomeAddress like I want. Theres also some more changes i have implemented to make it run smoother.

Related

Understanding File Handling I/O

I have written a simple program in two ways. The program is for getting data from a user, storing it in a txt file, retrieving the data and displaying it. The problem is that one approach works while the other does not. I dont understand why.
The one that works is this:
#include <iostream>
#include <fstream>
using namespace std;
class customer{
public:
// Declaring member variables and functions
string name, address, telNo;
int age;
void createCustomer();
void displayInfo(string inputName);
};
// Member function of customer to enter new customer details
void customer::createCustomer(){
customer c;
ofstream file;
file.open("customers.txt", ios::out);
cout << "Enter Name: ";
cin >> c.name;
cout << "Enter Age: ";
cin >> c.age;
cout << "Enter Address: ";
cin >> c.address;
cout << "Enter Telephone Number: ";
cin >> c.telNo;
file.write((char*)&c, sizeof(c));
file.close();
cout << "\n";
}
// Member function of customer to display customer information
void customer::displayInfo(string inputName){
customer c;
ifstream file;
file.open("customers.txt", ios::in);
if(!file){
cout << "Could Not Open customers.txt File\n";
return;
}
while(!file.eof()){
file.read((char*)&c, sizeof(c));
if (inputName == c.name){
cout << "\n";
cout << "Name-------------> " << c.name << endl;
cout << "Age--------------> " << c.age << endl;
cout << "Telephone Number-> " << c.telNo << endl;
cout << "Address----------> " << c.address << endl;
cout << "\n";
break;
}
}
file.close();
}
int main(){
customer c;
c.createCustomer();
c.displayInfo("name");
return 0;
}
It gives the following output:
Enter Name: name
Enter Age: 21
Enter Address: add
Enter Telephone Number: telno
Name-------------> name
Age--------------> 21
Telephone Number-> telno
Address----------> add
The one that doesnt work is this:
#include <iostream>
#include <fstream>
using namespace std;
class customer{
public:
// Declaring member variables and functions
string name, address, telNo;
int age;
void createCustomer();
void displayInfo();
};
// Member function of customer to enter new customer details
void customer::createCustomer(){
customer c;
ofstream file;
file.open("customers.txt", ios::out);
cout << "Enter Name: ";
cin >> c.name;
cout << "Enter Age: ";
cin >> c.age;
cout << "Enter Address: ";
cin >> c.address;
cout << "Enter Telephone Number: ";
cin >> c.telNo;
file.write((char*)&c, sizeof(c));
file.close();
cout << "\n";
}
// Member function of customer to display customer information
void customer::displayInfo(){
string inputName = "name";
customer c;
ifstream file;
file.open("customers.txt", ios::in);
if(!file){
cout << "Could Not Open customers.txt File\n";
return;
}
while(!file.eof()){
file.read((char*)&c, sizeof(c));
if (inputName == c.name){
cout << "\n";
cout << "Name-------------> " << c.name << endl;
cout << "Age--------------> " << c.age << endl;
cout << "Telephone Number-> " << c.telNo << endl;
cout << "Address----------> " << c.address << endl;
cout << "\n";
break;
}
}
file.close();
}
int main(){
customer c;
c.createCustomer();
c.displayInfo();
return 0;
}
All I have done is put the string inputName variable inside the function instead of passing it as an argument.
It gives only the following output:
Enter Name: name
Enter Age: 21
Enter Address: add
Enter Telephone Number: telno
If I remove the if condition:
while(!file.eof()){
file.read((char*)&c, sizeof(c));
//if (inputName == c.name){
cout << "\n";
cout << "Name-------------> " << c.name << endl;
cout << "Age--------------> " << c.age << endl;
cout << "Telephone Number-> " << c.telNo << endl;
cout << "Address----------> " << c.address << endl;
cout << "\n";
break;
//}
}
i get the following output:
Enter Name: name
Enter Age: 21
Enter Address: add
Enter Telephone Number: telno
Name-------------> 0∙⌂┼
Age--------------> 21
Telephone Number-> name
Address----------> §
Why are the name and address fields outputting random symbols and the telephone number field outputting value of the name field?
Neither program is correct. It's an error use read on a type like customer because it contains sub-objects that need constructing, namely the string members name, address and telNo. Calling read does not call any constructor for the objects you are reading and so this is invalid.
Since read does not work for strings it doesn't make any sense to use write on a class containing a string either because you won't be able to read back what you have written.
If you want to write a customer to a file you can do it something like this
file << c.name << ' ' << c.age << ' ' << c.telNo << ' ' << c.address << '\n';
and then something similar for reading (although you then you would have to be careful of any spaces in your data).

Addition of length of two words generates wrong answer(string0.length() + string1.length())

#include <iostream>
using std::cout;
using std::cin;
using std::string;
int main(){
cout << "Welcome to the program!";
cout << "\nWhat is your name? ";
string name;
cin >> name;
cout << "Hi, " << name << ". ";
cout << "Your name has " << name.length() << " letters!";
cout << "\nWhat is your last name? ";
string lastname;
string *plastname;
cin >> lastname;
plastname = &lastname;
cout << "Your full name is " << name.append(*plastname) << ".";
cout << " Your full name has " << name.length() + lastname.length() << " letters!";
return 0;
}
And this is the results:
Welcome to the program!
What is your name? adk
Hi, adk. Your name has 3 letters!
What is your last name? adkl
Your full name is adkadkl. Your full name has 11 letters!
How 3 + 4 = 11?!
First you do name.append(*plastname) which really appends lastname into name, making name a string of length 7 (with your example input).
Then you print name.length() + lastname.length() which is equal to 7 + 4 (remember the previous append you did!), leading to the result of 11.
Perhaps of appending name and lastname, you should print them separately? Like
cout << "Your full name is " << name << ' ' << lastname << ".\n";
You've appended lastname to name and then added them, that gives you a bigger value than expected
cout << "Your full name is " << name.append(*plastname) << ".";//You append here
cout << " Your full name has " << name.length() + lastname.length() << " letters!";//And then add here
you just print name.length() instaed of name.length() + lastname.lenght() as you already appended the lastname to name.

C++ GPA Trunc for 10 Students Input

I am able to enter the first student, however, once I request the second student's input it does not accept the: getline(cin, s2) on to getline(cin,s10).
Could you please help me understand where the mistake is made or why the output is not following the same format as s1/GPA1?
Here is my code:
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
//Welcome
cout << "Welcome to your personal GPA Calculator! \n" << endl;
float GPA1, GPA2, GPA3, GPA4, GPA5, GPA6, GPA7, GPA8, GPA9, GPA10 = 0;
string s1, s2, s3, s4, s5, s6, s7, s8, s9, s10;
//Requesting User Input
cout << "Student One| Please enter your Last Name, First Name: " << endl;
getline(cin, s1);
cout << "What is your current GPA: " << endl;
cin >> GPA1;
cout << endl;
cout << "Student Two| Please enter your Last Name, First Name: " << endl;
getline(cin, s2);
cout << "What is your current GPA: " << endl;
cin >> GPA2;
cout << endl;
cout << "Student Three| Please enter your Last Name, First Name: " << endl;
getline(cin, s3);
cout << "What is your current GPA: " << endl;
cin >> GPA3;
cout << endl;
cout << "Student Four| Please enter your Last Name, First Name: " << endl;
getline(cin, s4);
cout << "What is your current GPA: " << endl;
cin >> GPA4;
cout << endl;
cout << "Student Five| Please enter your Last Name, First: " << endl;
getline(cin, s5);
cout << "What is your current GPA: " << endl;
cin >> GPA5;
cout << endl;
cout << "Student Six| Please enter your Last Name, First Name: " << endl;
getline(cin, s6);
cout << "What is your current GPA: " << endl;
cin >> GPA6;
cout << endl;
cout << "Student Seven| Please enter your Last Name, First Name: " << endl;
getline(cin, s7);
cout << "What is your current GPA: " << endl;
cin >> GPA7;
cout << endl;
cout << "Student Eight| Please enter your Last Name, First Name: " << endl;
getline(cin, s8);
cout << "What is your current GPA: " << endl;
cin >> GPA8;
cout << endl;
cout << "Student Nine| Please enter your Last Name, First Name: " << endl;
getline(cin, s9);
cout << "What is your current GPA: " << endl;
cin >> GPA9;
cout << endl;
cout << "Student Ten| Please enter your Last Name, First Name: " << endl;
getline(cin, s10);
cout << "What is your current GPA: " << endl;
cin >> GPA10;
cout << endl;
//Store in Tabular Format
cout << ("Student Name| \t\t |Student GPA Value \n");
cout << ("____________________________________________\n");
std::cout << s1 << "\t\t " << std::setprecision(2) << std::fixed << GPA1 << endl;
std::cout << s2 << "\t\t " << std::setprecision(2) << std::fixed << GPA2 << endl;
std::cout << s3 << "\t\t " << std::setprecision(2) << std::fixed << GPA3 << endl;
std::cout << s4 << "\t\t " << std::setprecision(2) << std::fixed << GPA4 << endl;
std::cout << s5 << "\t\t " << std::setprecision(2) << std::fixed << GPA5 << endl;
std::cout << s6 << "\t\t " << std::setprecision(2) << std::fixed << GPA6 << endl;
std::cout << s7 << "\t\t " << std::setprecision(2) << std::fixed << GPA7 << endl;
std::cout << s8 << "\t\t " << std::setprecision(2) << std::fixed << GPA8 << endl;
std::cout << s9 << "\t\t " << std::setprecision(2) << std::fixed << GPA9 << endl;
std::cout << s10 << "\t\t " << std::setprecision(2) << std::fixed << GPA10 << endl;
return (0);
}
You generally don't want to read numbers directly with cin for interactive use. It doesn't play well with newlines -- leaving the newline for the next entry. In this case, you get a blank name for person 2.
Try this:
string temp;
//Requesting User Input
cout << "Student One| Please enter your Last Name, First Name: " << endl;
getline(cin, s1);
cout << "What is your current GPA: " << endl;
getline(cin, temp);
GPA1 = strtof(temp.c_str(), 0);
cout << endl;
You have to be careful when you mix cin and getline(cin, "string"). Cin will ignore any empty spaces or lines while getline will not. What's happening is that after you input the first student's GPA, a newline character is stored in the buffer and is carried over to getline where it's entered automatically. Try using cin.ignore() after every cin >> gpa.

when running program it has me enter two lines after name? help please

my program seems to want to enter two inputs for name variable instead of just entering one thing and moving on to phone number?
i'm sure its simple but can someone help me fix this please? is it something it do with the getline?
#include <iostream>
#include <string>
#include <vector>
using namespace std;
//define Car struct
struct Speaker
{
string name;
string phoneNumber;
string emailAddress;
string theme;
double fee;
};
Speaker *getSpeaker();
int main()
{
Speaker thespeaker;
thespeaker = *getSpeaker();
cout << "The speaker entered is!" << endl;
cout << thespeaker.name << endl;
cout << "phone number: " << thespeaker.phoneNumber << endl;
cout << "email: " << thespeaker.emailAddress << endl;
cout << "theme: " << thespeaker.theme << endl;
cout << "fees: " << thespeaker.fee << endl;
}
Speaker *getSpeaker()
{
Speaker *theSpeaker;
theSpeaker = new Speaker;
cout << "Please enter Speakers information" << endl;
cout << "name: " ;
getline(cin, theSpeaker->name);
cin.ignore(100, '\n');
cin.clear();
cout << theSpeaker->name;
cout << "\nphone number: ";
cin >> theSpeaker->phoneNumber;
cout << "\nEmail Address: ";
cin >> theSpeaker->emailAddress;
cout << "\nTheme: ";
cin >> theSpeaker->theme;
cout << "\nFee: ";
cin >>theSpeaker->fee;
return theSpeaker;
}
There's no need for cin.ignore();
Simply write it as:
Speaker *getSpeaker()
{
Speaker *theSpeaker;
theSpeaker = new Speaker;
cout << "Please enter Speakers information" << endl;
cout << "name: " ;
getline(cin, theSpeaker->name);
cout << theSpeaker->name;
cout << "\nphone number: ";
cin >> theSpeaker->phoneNumber;
cout << "\nEmail Address: ";
cin >> theSpeaker->emailAddress;
cout << "\nTheme: ";
cin >> theSpeaker->theme;
cout << "\nFee: ";
cin >>theSpeaker->fee;
return theSpeaker;
}

Error with fstream in C++

I'm writing a simple program to enter student records and store them in a coma delimited file. Everything looks good but when I run the program I get an error:
Error 1 error C2248: 'std::basic_ios<_Elem,_Traits>::basic_ios' : cannot access private member declared in class 'std::basic_ios<_Elem,_Traits>' c:\program files\microsoft visual studio 10.0\vc\include\fstream 1116 1 project1
Here's the code:
#include <cstring>
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
void closeOrNewRecordMenu(string enterAnotherRecord)
{
if (enterAnotherRecord == "Q" && enterAnotherRecord == "q")
{
exit(0);
}
}
void newStudentRecord(double studentNumber, string firstName, string lastName, string campus, string course1, string course2, string course3, string seniorPracticum, ofstream writeToRecordsFile)
{
int campusChoice;
do {
cout << "Student's six digit number: (Numeric only)";
cin >> studentNumber;
cin.ignore();
}
while (studentNumber < 100000 && studentNumber > 999999);
cout << "Student's first name: " << "\n";
cin >> firstName;
cin.ignore();
cout << "Student's last name: " << "\n";
cin >> lastName;
cin.ignore();
while (campusChoice < 1 || campusChoice > 3)
cout << "Which campus will " << firstName << " " << lastName << " be attending class at: " << "\n";
cout << "For the North campus enter 1" << "\n";
cout << "For the South campus enter 2" << "\n";
cout << "For the Seaside campus enter 3" << "\n";
cin >> campusChoice;
cin.ignore();
if (campusChoice == 1)
{
campus = "North Campus";
}
else if (campusChoice == 2)
{
campus = "South Campus";
}
else if (campusChoice == 3)
{
campus = "Seaside Campus";
}
else {
cout << "Please enter a valid choice." << "\n" << "\n";
}
cout << "Student's first course: " << "\n";
getline (cin, course1);
cin.ignore();
cout << "Student's second course: " << "\n";
getline (cin, course2);
cin.ignore();
cout << "Student's third course: " << "\n";
getline (cin, course3);
cin.ignore();
do {
cout << "Is " << firstName << " " << lastName << " a senior this year? Please enter \"Y\" for yes and \"N\" for no." << "\n";
cin >> seniorPracticum;
cin.ignore();
} while (seniorPracticum != "y" && seniorPracticum != "Y" && seniorPracticum != "n" && seniorPracticum != "N");
writeToRecordsFile << studentNumber << "," << firstName << "," << lastName << "," << campus << "," << course1 << "," << course2 << "," << course3 << "," << seniorPracticum << "\n";
cout << "The student record for " << firstName << " " << lastName << " has been saved." << "\n" << "\n";
}
int main()
{
cout << "Hello there! Welcome to the student record manager. From here you can enter new student information and save it to a file!!!! (More exciting to the developer than the user)." << "\n" << "\n";
string enterAnotherRecord;
ofstream writeToRecordsFile;
writeToRecordsFile.open("cop2224_proj1.txt");
while (enterAnotherRecord != "Q" && enterAnotherRecord != "q") {
cout << "Press \"N\" to create a new student record or press \"Q\" to quit." << "\n" << "\n";
cin >> enterAnotherRecord;
closeOrNewRecordMenu(enterAnotherRecord);
string firstName, lastName, seniorPracticum, campus, course1, course2, course3;
double studentNumber;
newStudentRecord(studentNumber, firstName, lastName, campus, course1, course2, course3, seniorPracticum, writeToRecordsFile);
}
writeToRecordsFile.close();
}
Streams are not copyable, and even if they were, you wouldn't want to do so here – pass by reference instead. Change your newStudentRecord signature to:
void newStudentRecord(double studentNumber, string firstName, string lastName, string campus, string course1, string course2, string course3, string seniorPracticum, ofstream& writeToRecordsFile);
That being said, why are you passing in all those arguments when you don't care about their initial values and you don't use them as output parameters? Simplify your signature to the following:
void newStudentRecord(ofstream& writeToRecordsFile);
and declare the other arguments as local variables inside of newStudentRecord.
As an aside, you're reading campusChoice before initializing it, which will yield undefined behavior.