(I'm just a guy trying to start programming so don't be too harsh, English is not my main language too)
I was trying to make a simple program about storing book into a library (with class since I started learning them) and the array won't show up in a different case other than the one in which I initialized it, the IDE doesn't show up any error too
Code:
#include <iostream>
using namespace std;
class MainMenu {
public:
int choice, ID, IDC;
string Name[500];
string Genre[500];
string Book[500];
void Menu() {
cout << "choose an action:" << endl;
cout << "1)\tadd a book\n2)\tsee my book" << endl;
cin >> choice;
switch (choice) {
case 1:
cout << "ID:" << endl;
cin >> ID;
cout << "name:" << endl;
cin >> Name[ID];
cout << "Genre" << endl;
cin >> Genre[ID];
cout << "> " << endl;
cin >> Book[ID];
cout << "<" << endl;
cout << "book successfully registered" << endl;
// assign a value about the book (name and genre) in each array stored
// with the id
break;
case 2:
cout << "ID?" << endl;
cin >> IDC; // IDC stands for ID Check, if ID == IDC then it should show
// the specs of the book + its content
cout << Name[IDC] << endl
<< Genre[IDC] << endl
<< "--> " << Book[IDC] << endl
<< endl;
break;
} // Switch
} // Menu
}; // Class
int main() {
int i = 0;
while (i == 0) // creating a loop to keep showing the menu without the end of
// the program
{
MainMenu giorgio;
giorgio.Menu(); // summoning menu
}
}
When you create a Object, all atributes are initialized, as a result, you create a emptiy arrays of your Object for each iteration, you can resolve this whit this code:
#include <iostream>
using namespace std;
class MainMenu {
public:
int choice, ID, IDC;
string Name[500];
string Genre[500];
string Book[500];
void Menu() {
cout << "choose an action:" << endl;
cout << "1)\tadd a book\n2)\tsee my book" << endl;
cin >> choice;
switch (choice) {
case 1:
cout << "ID:" << endl;
cin >> ID;
cout << "name:" << endl;
cin >> Name[ID];
cout << "Genre" << endl;
cin >> Genre[ID];
cout << "> " << endl;
cin >> Book[ID];
cout << "<" << endl;
cout << "book succesfully registered" << endl;
break;
case 2:
cout << "ID?" << endl;
cin >> IDC;
cout << Name[IDC] << endl
<< Genre[IDC] << endl
<< "--> " << Book[IDC] << endl
<< endl;
break;
}
}
};
int main() {
int i = 0;
MainMenu giorgio;
while (i == 0)
{
giorgio.Menu(); // summoning menu
}
}
The user is asked if s/he wants to return to main menu, if the user inputs n/N it only proceeds to the next solution when it should immediately end the program. Shown below is the code I used for the program. Please help me to make solution on how to end the program immediately when No is chosen as his/her choice. Thank you so much!
void number()
int b=0;
int groupChoice=0;
float ave[groupChoice];
int trials[groupChoice];
float result,sumRes,dAve;
int sumTry=0;
char choice;
cout << "\nNUMBER OF TRIALS" << endl;
cout << "\nHow many groups? ";
cin >> groupChoice;
for (int j=0;j<groupChoice;j++)
{
cout << "Average distance for group " << j+1 << ": ";
cin >> ave[j];
cout << "No. of trials for group " << j+1 << ": ";
cin >> trials[j];
}
cout << "\nGroups\t\tAve. Distance(x)\tNo. of trials(w)\tx(w)" << endl;
for (int i=0;i<groupChoice;i++)
{
result=ave[i]*trials[i];
cout << "Group " << i + 1 << "\t\t" << ave[i] << "\t\t\t" << trials[i] << "\t\t\t" << result << endl;
sumTry=sumTry+trials[i];
sumRes+=result;
}
cout << "\t\t\t\t\tSum = " << sumTry << "\t\tSum = " << sumRes << endl;
dAve = sumRes / sumTry;
cout << "Distance Average is " << dAve << endl << endl;
b=0;
while(b==0)
{
cout << "Would you like to return to main menu? [Y or N]: ";
cin >> choice;
if (choice=='Y'||choice=='y')
{
b++;
system("cls");
a=0;
main();
}
else if (choice=='N'||choice=='n')
{
b++;
break;
}
}
You can terminate your program with
void std::exit( int exit_code );
eg
std::exit(EXIT_SUCCESS);
https://en.cppreference.com/w/cpp/utility/program/exit
There are two options
use
std::exit(<exit_code>); or
std::_Exit(<exit_code>);
more info:
https://en.cppreference.com/w/c/program/_Exit
#include <iostream>
#include <fstream>
#include <iomanip>
#include <stdlib.h>
using namespace std;
struct football_game
{
string visit_team;
int home_score;
int visit_score;
};
void printMenu();
int main()
{
int i, totalValues = 0;
ifstream inputFile;
string temp = "";
inputFile.open("games.txt");
if (!inputFile)
{
cout << "Error opening Input file!" << endl;
exit(101);
}
inputFile >> totalValues;
getline(inputFile, temp);
cout << " *** Football Game Scores *** " << endl << endl;
cout << " * Total Number of teams : " << totalValues << endl << endl;
football_game* records = new football_game[totalValues];
// while (!inputFile.eof())
// {// == NULL) {
for (i = 0; i < totalValues; i++)
{
getline(inputFile, records[i].visit_team);
cout << records[i].visit_team << endl;
inputFile >> records[i].home_score >> records[i].visit_score;
cout << records[i].home_score << " " << records[i].visit_score << endl;
getline(inputFile, temp);
}
//}
cout << endl;
int choice = 0;
int avg_home_Score = 0;
int avg_visit_Score = 0;
printMenu(); // prints menu
cout << "Please Enter a choice from the Menu : ";
cin >> choice;
cout << endl << endl;
while (true)
{
switch (choice)
{
case 1:
cout << " Score Table " << endl;
cout << " ***********************" << endl << endl;
cout << " VISIT_TEAM"
<< " "
<< " HIGH_SCORE"
<< " "
<< "VISIT_SCORE " << endl;
cout << " -----------"
<< " "
<< "-----------"
<< " "
<< "------------" << endl;
for (int i = 0; i < totalValues; i++)
{
cout << '|' << setw(18) << left << records[i].visit_team << " " << '|'
<< setw(7) << right << records[i].home_score << " " << '|' << setw(7)
<< right << records[i].visit_score << " " << '|' << endl;
}
cout << endl << endl << endl;
break;
case 2:
{
string team_name;
cout << "Enter the Team Name : ";
cin >> team_name;
for (int i = 0; i < totalValues; i++)
{
if (records[i].visit_team == team_name)
{
cout << " VISIT_TEAM"
<< " "
<< " HIGH_SCORE"
<< " "
<< "VISIT_SCORE " << endl;
cout << " -----------"
<< " "
<< "-----------"
<< " "
<< "------------" << endl;
cout << '|' << setw(18) << left << records[i].visit_team << " " << '|'
<< setw(7) << right << records[i].home_score << " " << '|'
<< setw(7) << right << records[i].visit_score << " " << '|'
<< endl;
}
}
cout << endl;
break;
}
case 3:
{
for (int i = 0; i < totalValues; i++)
avg_home_Score += records[i].home_score;
cout << "Average home_score: " << (avg_home_Score / totalValues) << endl << endl;
break;
}
case 4:
{
for (int i = 0; i < totalValues; i++)
avg_visit_Score += records[i].visit_score;
cout << "Average visit_score: " << (avg_visit_Score / totalValues) << endl << endl;
break;
}
default:
{
cout << "Please enter valid input !!" << endl;
break;
}
}
printMenu();
cin >> choice;
}
return 0;
}
void printMenu()
{
cout << " Menu Options " << endl;
cout << " ================ " << endl;
cout << " 1. Print Information of all Games[Table Form] " << endl;
cout << " 2. Print Information of a Specific Game " << endl;
cout << " 3. Print Average points scored by the Home Team during season" << endl;
cout << " 4. Print Average points scored against the Home Team" << endl << endl << endl;
}
Here is the input file i am using
games.txt
5
SD Mines
21 17
Northern State
10 3
BYU
10 21
Creighton
14 7
Sam Houston State
14 24
When i am using the 2nd option (Print Information of a Specific Game) from the output screen,
it ask me to enter the team name and when i enter the team-name.
For example: SD Mines it gives me an error, but when I enter the team-name with no space like: BYU it works fine for me.
cin >> team_name;
Takes the input only upto space.
You might want to use cin.getline() for taking space separated strings as input.
A small program demonstrating the same :
#include <iostream>
#include <string>
int main ()
{
std::string name;
std::cout << "Please, enter your full name: ";
std::getline (std::cin,name);
std::cout << "Name is : , " << name << "!\n";
return 0;
}
std::cin ignores whitespaces by default.
To include spaces in your input try :
getline(cin, team_name);
This would pick up all the characters in a line until you press enter. This is available in
#include<string>
You need to flush the std::cin buffer after reading the choice:
#include <limits>
//...
cin >> choice;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
Refer to this question for detailed explanation.
Also, if you want to read strings with spaces from the standard input, replace this:
cin >> team_name;
with this:
getline(cin, team_name);
as already mentioned in other answers. No need to flush std::cin this time, since you have already read the full line.
Finally, remove extra newlines from your games.txt:
5
SD Mines
21 17
Northern State
...
I'm working on a program very important to my programming class, and there's something I can't quite figure out; When I try to read from a binary file I've created after opening the program, it fails even if the file's in the directory, and after I try to wipe the contents of the file, I can still 'read' them from the file even though said file is empty when I examine it in explorer. I've determined from this that even though I'm using BinaryFile.read, it's not truly reading from the file, and instead reading from variables stored in the program itself. How can I get my program to read from the actual file?
(please note that this is not yet a complete program, hence the commented sections and empty functions.)
(Also please note that, due to the nature of my class, I am only allowed to use what has been taught already (namely, anything in the fstream header and most things before which are necessary to make a basic program - he's letting me use things in stdio.h, as well.)
//
// main.cpp
// Binary Program
//
// Created by Henry Fowler on 11/19/14.
// Copyright (c) 2014 Bergen Community College. All rights reserved.
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <cstdlib>
#include <math.h>
#include <stdio.h>
using namespace std;
struct Record
{
char Name[20];
char LastName[20];
double Pay;
int Clearance;
int ID;
};
void CreateFile(fstream&); //Working
void CheckExist(fstream&); //Working
void Populate(fstream&,Record[],int&,int&); //Working
void Display(fstream&,Record[],int&,int&); //Working
void Append(fstream&,Record[],int&,int&); //Working
void DeleteFromFile(fstream&,fstream&,Record[],int&,int&);
// void SearchInFile(fstream&,Record[],int&,int&);
// void ModifyRecord(fstream&,Record[],int&,int&);
//void SortFile();
void WipeFile(fstream&);
void DelFile(fstream&);
int main(int argc, const char * argv[])
{
Record EmpRecords[20];
char Binary[] = "BinaryFile.dat";
char Binary2[] = "BinaryFileTemp.dat";
int maxsize; //make sure to set i to max size so you can use it later for things like wiping the file or deleting specific records
fstream BinaryFile;
fstream BinaryFile2;
string InputStr;
// char Read;
//int Choice = 0;
int i = 0;
int choice = 0;
int switchchoice;
CreateFile(BinaryFile); //working
CheckExist(BinaryFile); //working
BinaryFile.close();
while(choice==0)
{
cout << "Options: " << endl;
cout << "End Program (0)" << endl;
cout << "Input new records to file (1)" << endl;
cout << "Display current contents of file (2)" << endl;
cout << "Append a record at the end of the file (3)" << endl;
cout << "Delete a record from the file (4)" << endl;
cout << "Search for a record in the file (5)" << endl;
cout << "Modify a certain record (6)" << endl;
cout << "Sort file (unimplemented)" << endl;
cout << "Wipe contents of file (8)" << endl;
cout << "Please choose an option: ";
cin >> switchchoice;
switch(switchchoice)
{
case 0:
{
cout << "Exiting.";
BinaryFile.close();
system("PAUSE");
return 0;
break;
}
case 1:
{
Populate(BinaryFile, EmpRecords,i,maxsize); //working
break;
}
case 2:
{
Display(BinaryFile, EmpRecords,i,maxsize); //working i think
break;
}
case 3:
{
Append(BinaryFile, EmpRecords,i,maxsize); //working
break;
}
case 4:
{
DeleteFromFile(BinaryFile,BinaryFile2,EmpRecords,i,maxsize); //!
break;
}
case 5:
{
// SearchInFile(BinaryFile, EmpRecords,i,maxsize); //!
break;
}
case 6:
{
// ModifyRecord(BinaryFile, EmpRecords,i,maxsize); //!
break;
}
case 7:
{
cout << "Error, file sorting is currently unimplemented. Please try again.";
break;
}
case 8:
{
WipeFile(BinaryFile);
break;
}
}
}
system("PAUSE");
return 0;
}
void CreateFile(fstream& BinaryFile)
{
BinaryFile.open("BinaryFile.dat", ios::out | ios::binary);
}
void CheckExist(fstream &BinaryFile)
{
if(BinaryFile.good())
{
cout << endl << "File does exist" << endl;
}
else
{
cout << "file named can not be found \n";
system("PAUSE");
}
}
void Populate(fstream &BinaryFile,Record EmpRecords[],int &i, int &maxsize)
{
BinaryFile.open("BinaryFile.dat", ios::out | ios::binary);
int choice = 0;
while(choice==0)
{
cout << "Please input employee first name: ";
cin >> EmpRecords[i].Name;
cout << "Please input employee last name: ";
cin >> EmpRecords[i].LastName;
cout << "Please input Employee Pay: ";
cin >> EmpRecords[i].Pay;
cout << "Please input Employee Clearance (1-10): ";
cin >> EmpRecords[i].Clearance;
cout << "Please input Employee ID (6 numbers, i.e. 122934): ";
cin >> EmpRecords[i].ID;
cout << "Input another employee's information? (0) = yes, (1) = no: ";
cin >> choice;
BinaryFile.write((char *) (&EmpRecords[i]),sizeof(EmpRecords[i]));
i = i+1;
}
maxsize = i;
cout << "i is " << i << endl;
cout << "maxsize is " << maxsize << endl;
BinaryFile.close();
}
void Display(fstream &BinaryFile,Record EmpRecords[],int &i,int &maxsize)
{
BinaryFile.open("BinaryFile.dat", ios::in | ios::binary | ios::app);
int i2 = maxsize;
i = 0;
while(i2>0)
{
BinaryFile.read((char *) (&EmpRecords[i]),sizeof(EmpRecords[i]));
cout << i << endl;
cout << EmpRecords[i].Name << " " << EmpRecords[i].LastName << endl;
cout << "Pay: $" << EmpRecords[i].Pay << endl;
cout << "Clearance: " << EmpRecords[i].Clearance << endl;
cout << "Employee ID: " << EmpRecords[i].ID << endl;
BinaryFile.read((char *) (&EmpRecords[i]),sizeof(EmpRecords[i]));
cout << endl;
i2 = i2-1;
i = i+1;
}
BinaryFile.close();
}
void Append(fstream &BinaryFile,Record EmpRecords[],int &i,int &maxsize)
{
BinaryFile.open("BinaryFile.dat", ios::out|ios::binary|ios::ate|ios::app);
cout << "Please input employee first name: ";
cin >> EmpRecords[maxsize].Name;
cout << "Please input employee last name: ";
cin >> EmpRecords[maxsize].LastName;
cout << "Please input Employee Pay: ";
cin >> EmpRecords[maxsize].Pay;
cout << "Please input Employee Clearance (1-10): ";
cin >> EmpRecords[maxsize].Clearance;
cout << "Please input Employee ID (6 numbers, i.e. 122934): ";
cin >> EmpRecords[maxsize].ID;
cout << "Input another employee's information? (0) = yes, (1) = no: ";
BinaryFile.write((char *) (&EmpRecords[i]),sizeof(EmpRecords[i]));
maxsize = maxsize+1;
cout << "maxsize is " << maxsize << endl;
BinaryFile.close();
}
void DeleteFromFile(fstream &BinaryFile,fstream &BinaryFile2, Record EmpRecords[],int &i,int &maxsize)
{
BinaryFile.open("BinaryFile.dat", ios::out|ios::binary|ios::app);
BinaryFile2.open("BinaryFileTemp.dat", ios::out|ios::binary|ios::app);
int Choice;
cout << "Would you like to delete a file by name or by employee number?" << endl;
cout << "Name (1)" << endl;
cout << "Number (2)" << endl;
cout << "Choice: ";
cin >> Choice;
int i2 = maxsize;
if(Choice==1)
{
cout << "Please input employee first name: ";
// cin >> firstname;
cout << "Please input employee last name: ";
// cin >> lastname;
cout << "Searching...";
int i2 = maxsize;
i = 0;
while(i2>0)
{
BinaryFile.read((char *) (&EmpRecords[i]),sizeof(EmpRecords[i]));
cout << i << endl;
BinaryFile.read((char *) (&EmpRecords[i]),sizeof(EmpRecords[i]));
// if(EmpRecords[i].Name == firstname)
// {
// cout << "Found first name." << endl;
// if (EmpRecords[i].LastName == lastname)
// {
// cout << "Found last name." << endl;
/// }
// }
// else
// {
// cout << "Could not find name.";
// // BinaryFile2.write((char *) (&EmpRecords[i]),sizeof(EmpRecords[i]));
// }
cout << endl;
i2 = i2-1;
i = i+1;
}
}
BinaryFile.close();
if( remove( "BinaryFile.dat" ) != 0 )
cout << endl << "Error deleting file" << endl;
else
{
cout << "File successfully deleted" << endl << endl;
}
int result;
char oldname[]="BinaryFileTemp.dat";
char newname[]="BinaryFile.dat";
result = rename(oldname,newname);
if(result == 0)
cout << "DEBUG: Success" << endl;
else
cout << "DEBUG: Failure" << endl;
}
void WipeFile(fstream &BinaryFile)
{
int sure;
cout << "There is no undoing this action." << endl;
cout << "Continue (1)" << endl;
cout << "Cancel (2)" << endl;
cout << "Wipe file? ";
cin >> sure;
if(sure == 1)
{
cout << "Wiping file.";
BinaryFile.open("BinaryFile.dat", ios::out | ios::binary | ios::trunc);
BinaryFile.close();
}
else
{
cout << "Canceling.";
}
}
void DelFile(fstream &BinaryFile)
{
BinaryFile.close();
if( remove( "BinaryFile.dat" ) != 0 )
cout << endl << "Error deleting file" << endl;
else
{
cout << "File successfully deleted" << endl << endl;
}
}
Here the problem seems to be, even though you are wiping the file contents, you are not clearing the data you had stored in Record EmpRecords[20]; or the int maxsize value.
Few things you can do inside void WipeFile(fstream &BinaryFile) function: To keep it simple, we'll just reset maxsize to 0:
Pass the maxsize variable as reference to WipeFile(), the same way you are passing for Populate()
Update maxsize = 0, to indicate all the records are removed, when you delete the file contents.
It is better to memset the contents of EmpRecords as well similarly.
For now, I just modified your code to reset maxsize to 0 in WipeFile() and it worked.
void WipeFile(fstream &BinaryFile, int &maxsize)
{
int sure;
cout << "There is no undoing this action." << endl;
cout << "Continue (1)" << endl;
cout << "Cancel (2)" << endl;
cout << "Wipe file? ";
cin >> sure;
if(sure == 1)
{
cout << "Wiping file.";
BinaryFile.open("BinaryFile.dat", ios::out | ios::binary | ios::trunc);
BinaryFile.close();
maxsize = 0;
}
else
{
cout << "Cancelling.";
}
}
I have an Addressbook C++ program that compiles and everything, but I cannot figure out how to write it to a file that saves the data each time it exits. Here is my code:
//AddressBook Program
#include <iostream>
#include <string.h>
#include <cstdlib>
#include <stdio.h>
using namespace std;
class AddressBook{
public :
AddressBook()
{
count = 0;
}
void AddEntry();
void DisplayAll();
void DisplayEntry(int i); // Displays one entry
void SearchEntry();
int MainMenu();
struct Entry_Struct
{
char firstName[ 15 ] ;
char lastName[ 15 ] ;
char birthday[ 15 ] ;
char phone[ 15 ] ;
char email[ 15 ] ;
};
Entry_Struct entries[100];
unsigned int count;
};
void AddressBook::AddEntry()
{
cout << "Entry number " << (count + 1) << " : " << endl;
cout << "Enter First Name: ";
cin >> entries[count].firstName;
cout << "Enter Last Name: ";
cin >> entries[count].lastName;
cout << "Enter Date of Birth: ";
cin >> entries[count].birthday;
cout << "Enter Phone Number: ";
cin >> entries[count].phone;
cout << "Enter Email: ";
cin >> entries[count].email;
++count; // tally total entry count
}
void AddressBook::DisplayEntry(int i)
{
cout << "Entry[" << i + 1 << "] : " << endl; // states # of entry
cout << "First name : " << entries[i].firstName << endl;
cout << "Last name : " << entries[i].lastName << endl;
cout << "Date of birth : " << entries[i].birthday << endl;
cout << "Phone number : " << entries[i].phone << endl;
cout << "Email: " << entries[i].email << endl;
}
void AddressBook::DisplayAll()
{
cout << "Number of entries : " << count << endl;
for(int i = 0;i < count;++i)
DisplayEntry(i);
}
void AddressBook::SearchEntry()
{
char lastname[32];
cout << "Enter last name : ";
cin >> lastname;
for(int i = 0;i < count;++i)
{
if(strcmp(lastname, entries[i].lastName) == 0)
{
cout << "Found ";
DisplayEntry(i);
cout << endl;
}
}
}
// Your class
AddressBook my_book;
int MainMenu()
{
int num;
bool bQuit = false;
// Put all your code into a while loop.
while(bQuit == false)
{
cout << "+-------------------------------------+" << endl;
cout << "| Address Book Menu |" << endl;
cout << "| |" << endl;
cout << "| 1- Add an entry |" << endl;
cout << "| 2- Search for an entry by last name |" << endl;
cout << "| 3- Display all entries |" << endl;
cout << "| 4- Exit |" << endl;
cout << "| |" << endl;
cout << "+-------------------------------------+" << endl;
cout << endl;
cout << "Please enter a number for one of the above options: ";
cin >> num;
cout << endl;
if (num == 1)
my_book.AddEntry();
else if (num == 2)
my_book.SearchEntry();
else if (num == 3)
my_book.DisplayAll();
else if (num == 4)
bQuit = true;
else
cout << "Invalid choice. Please try again" << endl;
cout << endl;
}
return 0;
}
int main (){
MainMenu();
return 0;
}
I've gone over my textbook all day and nothing I'm doing is working.
Here is a basic example of opening, and writing an output file,
// basic file operations
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream outfile;
outfile.open ("addressbook.txt");
outfile << "Daffy,Duck,123 Main Street,Anytown,OH,USA,123-456-7890\n";
myfile.close();
return 0;
}
You need to have an inserter for your class. It's done using operator <<:
// Inside your class:
friend std::istream& operator<<(std::ostream& os, const AddressBook ab)
{
return os << /* ... */
}
As you can see, a user-defined operator << can be implemented in terms of the pre-defined standard inserter. You can use it in the following way:
std::ifstream in("yourtxtfile.txt");
in << my_book;