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.
Related
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).
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.
i'm trying to load the file into an array when the program starts so i can
modify or search in it i don't know if my code works or not ( it's not reading the file )i have the file
and there's two books in
i have tried to debug it but couldn't find the problem the code works
but it think there's a problem with the load() function i don't know what
my code :
#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
using namespace std;
struct books{
//identfying books with all needed things
int id, status;
string title, p_name, p_address;
string date;
string aut_name, aut_nationality;
}newbook[10000], aut[10000];
int i = 0;
void load(){
ifstream myfile("books.txt", ios::in);
while (myfile >> newbook[i].id >> newbook[i].title >> newbook[i].p_name >> newbook[i].p_address >> aut[i].aut_name >> aut[i].aut_nationality >> newbook[i].date >> newbook[i].status)
i++;
}
void search_for_book(){
int temp = 0;
int idx;
cout << "enter the ID of the book you're looking for : ";
cin >> idx;
for (int srh = 0; srh < i; srh++){
if (newbook[srh].id == idx){
cout << setw(10) << "book found :" << endl;
cout << "title :" << newbook[srh].title << endl;
cout << "publisher name : " << newbook[srh].p_name << endl;
cout << "publisher address" << newbook[srh].p_address << endl;
cout << "author name :" << aut[srh].aut_name << endl;
cout << "author Nationality :" << aut[srh].aut_nationality << endl;
cout << "publish Date :" << newbook[srh].date << endl;
cout << "status :" << newbook[srh].status << endl;
temp++;
break;
}
else
srh++;
}
if (temp == 0){
cout << "couldn't find book" << endl << endl;
}
}
int main(){
load();
char choice;
cout << "enter your choice (3)";
cin >> choice;
if (choice == '3'){
search_for_book();
}
}
note :*( there are other functions like adding new book but not necessary to write )
*(i'm new to c++ don't really know how to read file into memory but i'm trying)
this is the code to save data into file :
void add_new_book_5(){
int booksnumber;
books newbook[1000], aut[100];
cout << "how many books you want to add ? ";
cin >> booksnumber;
cout << "what books you want to add :" << endl;
d_base.open(path, ios::out | ios::app);
for (int i = 0; i < booksnumber; i++){
cout << "id please : "; cin >> newbook[i].id;
cout << "title : "; cin.ignore(); getline(cin, newbook[i].title);
cout << "publisher name :"; getline(cin, newbook[i].p_name);
cout << "publisher address : "; getline(cin, newbook[i].p_address);
cout << "author" << " name : "; cin.ignore(); getline(cin, newbook[i].aut_name);
cout << "Nationality : "; getline(cin, newbook[i].aut_nationality);
cout << "Publish date :"; getline(cin, newbook[i].date);
cout << "How many copies of " << newbook[i].title << " "; cin >> newbook[i].status;
system("cls");
d_base << newbook[i].id << "\ " << newbook[i].title << "\ ";
d_base << newbook[i].p_name << "\ " << newbook[i].p_address << "\ ";
d_base << newbook[i].aut_name << "\ " << newbook[i].aut_nationality << "\ ";
d_base << newbook[i].date << "\ " << newbook[i].status << endl;
}
d_base.close();
cout << setw(76) << "Books Have Been Saved Sucessfully" << endl;
}
I really have no idea, how to explain this question. But here it is...
Suppose I have an external text file, and it's content goes like this:
1 Crysis 2012 Crytek Ubisoft
2 FarCry 2009 Crytek Ubisoft
3 Need_For_Speed 1695 EA Ubisoft
4 Assassin'sCreed 2008 Ubisoft Ubisoft
5 COD 2010 Activision Ubisoft
then i've used this code:
if (fout.is_open())
{
std::string delim = " ";
size_t pos = 0;
std::string token;
while (getline(fout, line))
{
while ((pos = line.find(delim)) != std::string::npos)
{
token = line.substr(0, pos);
std::cout << token << std::endl;
line.erase(0, pos + delim.length());
}
std::cout << line << std::endl;
}
}
this code splits the text lines and outputs the following
1
Crysis
2012
Crytek
Ubisoft
2
FarCry
2009
Crytek
Ubisoft
3
Need_For_Speed
1695
EA
Ubisoft
4
Assassins'sCreed
2008
Ubisoft
Ubisoft
5
COD
2010
Activision
Ubisoft
What I actually want is to create a new structure in each loop and create it's 5 variables to hold each of the porperties for every individual game. For Example
struct Game
{
int id;
string title;
int year;
string developer;
string publisher;
};
Now from the output:
1
Crysis
2012
Crytek
Ubisoft
As the loop runs I want to create a new "Game" Structure and assign these values to it's variables and then push the structure in to a vector.
Here is a summary of what I am trying to create and how far I have come:
The program is a database of games. The user is able to add,delete,search and edit any item from the database. As the program runs and the user adds a Game it successfully gets written in the external .txt file and also get pushed to the end of the vector. Now that is all fine. But when I close the program and run it again, there is data in the text file but the vector is empty. So i want the vector to get populated again with the data in the .txt file, so that the user can continue working with the database.
I dont know if I explained the problem well enough. Or I might have over explained it. I am actually a noob in C++.
Thanks in advance..
here is the full code for the program i am working on...
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
struct Game
{
int id;
int year;
string title;
string publisher;
string developer;
};
void ShowData(vector<Game> myDatabase)
{
cout << endl;
for(size_t i = 0; i <= myDatabase.size()-1; i++)
{
cout << endl;
cout << "-------------------------------------------------------"<<endl;
cout << " ITEM NO" << " " << i + 1 << " " <<endl;
cout << "-------------------------------------------------------"<<endl;
cout << " TITLE: " << myDatabase[i].title << endl;
cout << " YEAR: " << myDatabase[i].year << endl;
cout << "DEVELOPER: " << myDatabase[i].developer << endl;
cout << "PUBLISHER: " << myDatabase[i].publisher << endl;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
string option;
int serialNumber = 0;
int count = 0;
string line;
vector<Game> Database;
fstream fout;
fout.open("Database.txt");
if (fout.is_open())
{
std::string delim = " ";
size_t pos = 0;
std::string token;
while (getline(fout, line))
{
Game newGame;
std::cout << line << std::endl;
}
while (getline(fout, line))
{
while ((pos = line.find(delim)) != std::string::npos)
{
token = line.substr(0, pos);
std::cout << token << std::endl;
line.erase(0, pos + delim.length());
}
std::cout << line << std::endl;
}
}
else
{
cout << "There was an error opening the file.";
}
cout << endl;
repeat:
cout << endl;
cout << "ADD | SHOW | DELETE | EDIT | SEARCH " << endl;
cout << "SAY : ";
cin >> option;
if(option == "ADD" || option == "Add" || option == "add")
{
serialNumber += 1;
Game NewGame;
NewGame.id = serialNumber;
cout << endl << "Name: ";
cin >> NewGame.title;
cout << "Year: ";
cin >> NewGame.year;
cout << "Developer: ";
cin >> NewGame.developer;
cout << "Publisher: ";
cin >> NewGame.publisher;
cout << endl;
Database.push_back(NewGame);
cout << endl;
cout << "Size is: " << Database.size();
fout << serialNumber << " " << Database[Database.size() - 1].title << " " << Database[Database.size() - 1].year << " "<< Database[Database.size() - 1].developer << " " << Database[Database.size() - 1].publisher << endl;
goto repeat;
}
if (option == "SHOW" || option == "Show" || option == "show")
{
ShowData(Database);
goto repeat;
}
if(option == "DELETE" || option == "Delete" || option == "delete")
{
int choose;
cout << "Delete Item No: ";
cin >> choose;
Database.erase(Database.begin() + (choose - 1));
cout << endl;
ShowData(Database);
goto repeat;
}
if(option == "SEARCH" || option == "Search" || option == "search")
{
cout << "Search By [ID, TITLE, YEAR, DEVELOPER, PUBLISHER] : ";
string choose;
cin >> choose;
if(choose == "ID" || choose == "Id" || choose == "id")
{
int idNumber;
cout << "ID No: ";
cin >> idNumber;
cout << endl;
cout << "ITEM NO" << "[" << idNumber << "]" <<endl;
cout << " TITLE: " << Database[idNumber - 1].title << endl;
cout << " YEAR: " << Database[idNumber - 1].year << endl;
cout << "DEVELOPER: " << Database[idNumber - 1].developer << endl;
cout << "PUBLISHER: " << Database[idNumber - 1].publisher << endl;
goto repeat;
}
else if (choose == "TITLE" || choose == "Title" || choose == "title")
{
string whatTitle;
cout << "Enter Title: ";
cin >> whatTitle;
for(size_t i = 0; i <= Database.size()-1; i++)
{
if(Database[i].title == whatTitle)
{
cout << endl;
cout << "ITEM NO" << "[" << i + 1 << "]" <<endl;
cout << " TITLE: " << Database[i].title << endl;
cout << " YEAR: " << Database[i].year << endl;
cout << "DEVELOPER: " << Database[i].developer << endl;
cout << "PUBLISHER: " << Database[i].publisher << endl;
}
}
goto repeat;
}
else if (choose == "YEAR" || choose == "Year" || choose == "year")
{
int whatYear;
cout << "Enter Year: ";
cin >> whatYear;
for(size_t i = 0; i <= Database.size()-1; i++)
{
if(Database[i].year == whatYear)
{
cout << endl;
cout << "ITEM NO" << "[" << i + 1 << "]" <<endl;
cout << " TITLE: " << Database[i].title << endl;
cout << " YEAR: " << Database[i].year << endl;
cout << "DEVELOPER: " << Database[i].developer << endl;
cout << "PUBLISHER: " << Database[i].publisher << endl;
}
}
goto repeat;
}
else if (choose == "DEVELOPER" || choose == "Developer" || choose == "developer")
{
string whatDeveloper;
cout << "Enter Developer Name: ";
cin >> whatDeveloper;
for(size_t i = 0; i <= Database.size()-1; i++)
{
if(Database[i].developer == whatDeveloper)
{
cout << endl;
cout << "ITEM NO" << "[" << i + 1 << "]" <<endl;
cout << " TITLE: " << Database[i].title << endl;
cout << " YEAR: " << Database[i].year << endl;
cout << "DEVELOPER: " << Database[i].developer << endl;
cout << "PUBLISHER: " << Database[i].publisher << endl;
}
}
goto repeat;
}
else if (choose == "PUBLISHER" || choose == "Publisher" || choose == "publisher")
{
string whatPublisher;
cout << "Enter Publisher Name: ";
cin >> whatPublisher;
for(size_t i = 0; i <= Database.size()-1; i++)
{
if(Database[i].publisher == whatPublisher)
{
cout << endl;
cout << "ITEM NO" << "[" << i + 1 << "]" <<endl;
cout << " TITLE: " << Database[i].title << endl;
cout << " YEAR: " << Database[i].year << endl;
cout << "DEVELOPER: " << Database[i].developer << endl;
cout << "PUBLISHER: " << Database[i].publisher << endl;
}
}
goto repeat;
}
}
if (option == "EDIT" || option == "Edit" || option == "edit")
{
int whichItem;
cout << "Enter Item No: ";
cin >> whichItem;
cout << endl << "Name: ";
string name;
cin >> name;
Database[whichItem - 1].title = name;
cout << "Year: ";
int year;
cin >> year;
Database[whichItem - 1].year = year;
cout << "Developer: ";
string developer;
cin >> developer;
Database[whichItem - 1].developer = developer;
cout << "Publisher: ";
string publisher;
cin >> publisher;
Database[whichItem - 1].publisher = publisher;
cout << endl;
ShowData(Database);
goto repeat;
}
fout.close();
system("PAUSE");
return 0;
}
You can create a struct as shown here.
In the example, they have an array of structs. In order to access an element of the struct use the . operator.
In C++11, you can use a tuple, instead of a struct.
Tuple vs Struct - Stackoverflow.
The idea is that the first can provide more generic operations, while the second has far better readability and you do not have to remember the order of your data members, IMHO.
[EDIT]
AS R. Hasan states, the question is a duplicate of this question.
I am not sure that's what you are looking for, but consider this (and don't forget to include vector)
First, we define custom structure
struct Game //your structure
{
int id;
std::string title;
int year;
std::string developer;
std::string publisher;
};
Now we overload operator>> (it's similar to using cin >> someVariable). Fstream already has methods to write in variables of standard types.
bool operator>>(std::fstream& fs, Game& g)
{
if (fs >> g.id >> g.title >> g.year >> g.developer >> g.publisher)
return true;
return false;
}
/*
fs >> g.id >> g.title equals (fs.operator>>(g.id)).operator>>(g.title) ...
*/
Standard operator>> returns reference to fstream, so we are able to write everything in just 1 line of code. If writing does fail (e.g. end of file reached) we return false.
std::vector<Game> vec;
STL vector
- standard container, that contains your Game structs
if (fout.is_open())
{
for ( ; ; )
{
Game g; //creating instantiation of your struct Game
if (fout >> g) //reading from your file
vec.push_back(g); //1 of STL vector methods, check link to cppreference higher
else //if reading fails, we break our infinite loop
break;
}
}
for (auto x : vec) //going through every element of our vector.
cout << x.id << " "; //and printing first variable of your structure
I have this code where the string info is not working as it should.
I have a getline where info is inside and it saves a hole sentence, but it won't output more than the first word.
Example:
"Hello world!"
I will only show me "hello"
Here is the part of the code:
void add() {
string name;
string faction;
string classe;
string race;
string info;
ofstream wowdatabase("wowdatabase.txt", ios::app);
cout << "Add a race or class" << endl;
cout << "---------------------------------------------------------" << endl;
cout << "" << endl;
cout << "Enter the name of the race or class (only small letters!):" << endl;
cin >> name;
cout << "Enter Race (Type -, if writen in name section):" << endl;
cin >> race;
cout << "Enter Class (Type -, if writen in name section):" << endl;
cin >> classe;
cout << "Enter faction (Alliance/Horde):" << endl;
cin >> faction;
cin.ignore( numeric_limits<streamsize>::max(), '\n' );
cout << "Enter the information:" << endl;
getline(cin, info);
cout << info;
system("pause");
wowdatabase << name << ' ' << faction << ' ' << classe << ' ' << race << ' ' << info << endl;
wowdatabase.close();
system("CLS");
main();
}
void searchname() {
ifstream charecter("wowdatabase.txt");
string name;
string find;
string faction;
string classe;
string race;
string info;
int i = 0;
system("CLS");
cout << "Search for a race or class" << endl;
cout << "---------------------------------------------------------" << endl;
cout << "" << endl;
cout << "Please enter name:";
cin >> find;
while (charecter >> name >> faction >> classe >> race >> info ) {
if (find == name) {
system("CLS");
cout << "Charecter found" << endl;
cout << "---------------------------------------------------------" << endl;
cout << "" << endl;
cout << "Name of race/class: " << name << endl;
cout << "Race: " << race << endl;
cout << "Class: " << classe << endl;
cout << "Faction: " << faction << endl;
cout << "Info: " << info << endl;
cout << "" << endl;
cout << "Press enter to return to menu" << endl;
system("pause");
system("CLS");
main();
}
}
You use variable info in several functions. For example in function searchname() you enter it as
while (charecter >> name >> faction >> classe >> race >> info )
that is in this function you do not use getline. Also your code is invalid because you may not recursively call main in C++.