I have been trying to do this all day but something is just not OK. I'm trying to make a system that reads students from text file and creates three new files. The three files are: Normal, Failed, New. Everything depends of the student's number. If it has 'D' in the beginning the student should go to the file with failed students. If there is 'I' in front of the number the student should go to the file named "New". If there is nothing in the beginning the student should go to the "Normal" file.
The problem is that if the students data is inserted manually to the file by the user everything is ok. But I have a function that reads student's data and inserts it in the main file. If there is nothing in front of the number everything is ok when I try to read all students from the file. But if there is a letter, the data is not being written in the proper(any) file.
Here is example: Let's have a ready file with data in it:
989123 John Brown //Should go to the "Normal" file
I112233 Steve Round //Should go to the "New" file
D101010 Wayne Bruce //Should go to the "Failed" file
And if I try to read the data and insert it into the proper files everything is ok.
But let's say that the user has choosed the "Add student" option from the applications menu. And the user inserts a new record. For example:
D818181 Some Guy //Should go to the "Failed" file
but it doesn't go there. I don't know what's the reason. If the user has entered a student number without any letter everything is OK but if there is a letter it is not shown in the file. I hope you got my mind. Here is the code. Every help will be appreciated.
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
struct Student
{
int number;
string name;
string secondName;
};
Student Failed[50], New[50], Normal[50];
int o = -1;
int v = -1;
int n = -1;
int MakeInt(string number, bool ignoreFirst)
{
int num;
if(ignoreFirst)
{
number[0] = '0';
num = atoi(number.c_str());
}
else
{
num = atoi(number.c_str());
}
return num;
}
void zapis_student(string number, string name, string secondName)
{
if(number[0] == 'D')
{
int num = MakeInt(number, true);
Student temp;
temp.number = num;
temp.name= name;
temp.secondName = secondName;
o++;
Failed[o] = temp;
}
else if(number[0] == 'I')
{
int num = MakeInt(number, true);
Student temp;
temp.number = num;
temp.name = name;
temp.secondName = secondName;
v++;
New[v] = temp;
}
else
{
int num = MakeInt(number, false);
Student temp;
temp.number = num;
temp.name = name;
temp.secondName = secondName;
n++;
Normal[n] = temp;
}
}
void ReadFile()
{
ifstream fp("studenti.txt", ios::in);
if(fp.fail())
{
cout<<"Error!"<<endl;
}
while(fp.good())
{
string number, name, secondName;
fp >> number >> name >> secondName;
zapis_student(number, name, secondName);
}
fp.close();
}
void sortir(Student a[], int br)
{
for(int i = 0; i < br; i++)
{
for(int j = 0; j < br-1; j++)
{
if(a[j].number>a[j+1].number)
{
Student buf = a[j];
a[j] = a[j+1];
a[j+1] = buf;
}
}
}
}
void MakeFile(Student a[], int br, char ime_fail[])
{
ofstream fp(ime_fail);
for(int i = 0; i < br; i++)
{
fp << a[i].number << " " << a[i].name << " " << a[i].secondName << endl;
}
fp.close();
}
void AddStudent()
{
fstream fp("studenti.txt", ios::app);
string number, firstName, secondName;
cin >> number >> firstName >> secondName;
fp << number << " " << firstName << " " << secondName << endl;
fp.close();
}
void SortStudents()
{
sortir(Failed, o);
sortir(New, v);
sortir(Normal, n);
}
int main ()
{ int ans;
do
{ cout<<"******************************Menu***********************************"<<endl;
cout<<"* *"<<endl;
cout<<"* 1. Add student. *"<<endl;
cout<<"* 2. Read file. *"<<endl;
cout<<"* 3. Sort students. *"<<endl;
cout<<"* 4. Make Normal file. *"<<endl;
cout<<"* 5. Make Failed file. *"<<endl;
cout<<"* 6. Make New file. *"<<endl;
cout<<"* 7. Exit! *"<<endl;
cout<<"* *"<<endl;
cout<<"*********************************************************************"<<endl;
cout<<endl<<"Choice: "<<endl;
do
{cin>>ans;} while((ans<1)||(ans>7));
switch(ans)
{ case 1:AddStudent();break;
case 2:ReadFile();break;
case 3:SortStudents();break;
case 4:MakeFile(Normal, n, "Normal.txt");cout<<"Suzdaden e fail NovaGrupa.txt!\n";break;
case 5:MakeFile(Failed, o, "Failed.txt");cout<<"Suzdaden e fail Izklucheni.txt!\n";break;
case 6:MakeFile(New, v, "New.txt");cout<<"Suzdaden e fail Vlizashti.txt!\n";break;
case 7:exit(1);
}
}
while(ans!=7);
}
You have just one single student per type; since you start from -1, you finish the reading with 0, which is the right index for the first element but the wrong count of elements! To fix this, I simply suggest you to start with 0, use the index and then increment. E.g.
int o = 0;
...
Failed[o] = temp;
o++;
(swapped the lines), so that o keeps the count of how many student of that kind you've read so far.
Note: you also need to handle properly the end of file and cope with the case when there's nothing that can be converted to an integer by atoi: you try anyway (and you don't have a way to notice it), and the "normal" count can be one unit greater (after the fix; before the fix, it's the correct count!)
Other suggestions
Do not use atoi (for which you should include cstdlib, and you don't)… do not ignore compiler warnings
Last argument of MakeFile should be const char *
Use better names for variable: o, v, n are poorly named.
Related
This is only a small part from my code. What I'm trying to do is writing at the end of the file (add record) which in this case is "books.txt" that already has 40 records. But when I debug, it would still prompt the user to enter isbn code but after entering, (process 3296) exited with code 3. came out. Which part am I doing wrong? The counter() function is to count how many records I already have in my file. And I'm also using array of struct to store my records.
int add_record(DATA book[])
{
int count = counter();
system("CLS");
cout << "\t\t\t\t\t\t\t\t : :Add Book Record: :\n\n";
bool cont;
ofstream outfile("books.txt", ios::app);
if (outfile.is_open() && !outfile.eof())
{
do
{
cont = true;
cout << "ISBN Code: ";
cin.getline(book[++count].isbn_code, 14, '\n');
//cin.ignore(numeric_limits<streamsize>::max(), '\n');
int length = strlen(book[++count].isbn_code);
for (int i = 0; i <= length; i++)
{
if (!isdigit(book[++count].isbn_code[i]))
{
cont = false;
cout << "Your input is invalid. Enter again.\n";
break;
}
}
} while (cont == false);
do
{
cont = true;
cout << "Author: ";
cin.getline(book[++count].author, 50, '\n');
int length = strlen(book[++count].author);
for (int i = 0; i <= length; i++)
{
if (isdigit(book[++count].author[i]))
{
cont = false;
cout << "Your input is invalid. Enter again.\n";
break;
}
}
} while (cont == false);
outfile << book[++count].isbn_code << "," << book[++count].author ;
outfile.close();
}
else
cout << "File is not open\n";
return 0;
}
Yes, the error message is completely correct. This is a rare case where using a cast is the correct thing to do
if (isdigit(static_cast<unsigned char>(book[++count].author[i])))
Reference, https://en.cppreference.com/w/cpp/string/byte/isdigit
But this has nothing to do with your crash which is caused by other errors. For instance
cin.getline(book[++count].isbn_code, 14, '\n');
//cin.ignore(numeric_limits<streamsize>::max(), '\n');
int length = strlen(book[++count].isbn_code);
You definitely don't want to increment count twice. I would guess the correct code is
cin.getline(book[count].isbn_code, 14, '\n');
int length = strlen(book[count].isbn_code);
and to increment count once later in your loop.
Remember ++count is not the same as count + 1. The first increments the count variable, that is it changes the value of the count variable, but count + 1 just adds one to count and does not change the value of the count variable.
This is also wrong
for (int i = 0; i <= length; i++)
In C++ string indexes start at zero and go upto the length of the string minus one, so the correct code is
for (int i = 0; i < length; i++)
Also not part of your question but X can be a legal character in an ISBN.
I've created a class called "Person" which holds a name, three sets of high scores and a picture link. I am reading from a text file that contains all of these variables and create several "Person" objects accordingly,then put them into a vector of "Person" objects.
This is the function that takes in an empty vector and outputs a vector with Persons added.
void input_data(vector<Person>& input){
ifstream ifs("personData.txt");
while (true) {
if (ifs.eof()) {
return;
}
Person n;
string name;
string picture;
string check;
int t1;int t2;int t3;
int r1;int r2;int r3;
int f1;int f2;int f3;
getline(ifs,name); // use getline to deal with spaces
getline(ifs,picture); // use getline to deal with spaces
ifs >> t1 >> t2 >> t3;
ifs >> r1 >> r2 >> r3;
ifs >> f1 >> f2 >> f3;
ifs.ignore(100, '\n');
getline(ifs,check); // use getline to deal with spaces
n.setName(name);
n.setPic(picture);
n.addScore(3, t1);n.addScore(3, t2);n.addScore(3, t3);
n.addScore(4, r1);n.addScore(4, r2);n.addScore(4, r3);
n.addScore(5, f1);n.addScore(5, f2);n.addScore(5, f3);
input.push_back(n);
if(check == ""){
cout << endl << "breaking" << endl;
break;
}
}
}
As you can see, using the "addScore" function, I intend to change the vector of scores in each Person according to the inputted type (3, 4 , or 5). Here is the Person class that is use. The logic for adding the values to the vector is used to maintain a size of 3 in each vector, and so I add the new value to the vector, sort it, and then delete the smallest entry. This gives me tht top three high scores.
class Person{
private:
//basic member functions
string name;
string pic;
vector<int> highThree;
vector<int> highFour;
vector<int> highFive;
public:
//constructor jsut makes eveything zero
Person(string m_name = "", string m_pic = ""):
name(m_name),
pic(m_name),
//initializing every vector to three instnace of 0
highThree(3,0),
highFour(3,0),
highFive(3,0){}
//manipulating member functionsjj
void setName(string i_name){name = i_name;}
string getName(){return name;}
void setPic(string i_pic){pic = i_pic;}
string getPic(){return pic;}
//logic for adding to the highschores
void addScore(int gameType, int val){
//(which is sorted), then add it and sort it again
if (gameType == 3){
//name = "yo";
highThree.push_back(val);
//sort the vector
sort(highThree.begin(), highThree.end());
//erase the first thing
highThree.erase(highThree.begin());
}
if (gameType == 4){
highFour.push_back(val);
sort(highFour.begin(), highFour.end());
highFour.erase(highThree.begin());
//cout << val << endl;
}
if (gameType == 5){
highFive.push_back(val);
sort(highFive.begin(), highFive.end());
highFive.erase(highThree.begin());
//cout << val << endl;
}
}
//gets the three score vecotors
vector<int>& getScores(int gameType){
if (gameType == 3){
for(int i = 0; i<highThree.size(); i++){
cout << highThree[i] << endl;
}
return highThree;
}else if(gameType == 4){
return highFour;
}else if(gameType == 5){
return highFive;
}else{
cout << "error in getScores input\n";
vector<int> bad;
return bad;
}
}
};
In main, when I try to access the scores in one of these member vectors, I get results that are not accurate to what I took in from the file. In fact, I printed out my input values in the "addScore" function as well as in the "input_data" function, and they are correct. This means that I'm getting data from the file accurately, but there is something wrong afterword.
int main(){
vector<Person> peeps;
input_data(peeps);
//the value that i get below is wrong
cout << peeps[0].getScores(3)[0];
}
The value that I get in the print above is 0, when it should be 8
. The text file that I'm reading from is attached below. I apologize for a such a long post, but I've spoken to all of my team mates about the issue and cant seem to figure out what is going wrong. There seems to be an issue with retrieving the contents of the member vector, but I cant find the issue.
bob
mypic
8 9 10
3 4 5
2 7 6
I'm trying to processes values from two text files.One holds a set of chars and the other holds a set of integers.each in their respective places in the text file will amount to one test case.For example the first value that is read in each text file is 1 test case.The values are then used to be checked for variability then Which will then be used as variables through out my code.then in the end prints out a double. The issue is I do not know how to reach that second iteration of test cases. All my code does is read the first values of each text file and prints out the double i need but for only the first test case. As i was typing this out i thought of maybe deleting the values once they are done being used then rerunning the program by having my main in a for loop? suggestions?
#include <iostream>
#include <fstream>
using namespace std;
//function prototypes
char getPackage();
bool vaildPackage(char);
int getHours();
bool validHours(int);
double calculatePakg_A(int);
double calculatePakg_B(int);
double calculatePakg_C(int);
void showBill(double);
int main()
{
char Package = getPackage();
int Hours = getHours();
double bill;
switch (Package)
{
case 'A':bill = calculatePakg_A(Hours);
cout << bill << endl;
break;
case 'B':bill = calculatePakg_B(Hours);
cout << bill << endl;
break;
case 'C':bill = calculatePakg_C(Hours);
cout << bill << endl;
break;
case 'a':bill = calculatePakg_A(Hours);
cout << bill << endl;
break;
case 'b':bill = calculatePakg_B(Hours);
cout << bill << endl;
break;
case 'c':bill = calculatePakg_C(Hours);
cout << bill << endl;
break;
default: cout << "you did not enter a valid Service Plan. \n";
break;
}
return 0;
}
char getPackage()
{
ifstream inputFile;
char a;
inputFile.open("Packages.txt");
do
{
inputFile >> a;
} while (! vaildPackage(a));
return a;
}
bool vaildPackage(char a)
{
return a == 'a' || a == 'A'|| a == 'B' || a == 'b'|| a == 'C' || a == 'c';
}
int getHours()
{
ifstream inFile;
int n;
inFile.open("Hours.txt");
do
{
inFile >> n;
} while (! validHours(n));
return n;
}
bool validHours(int n)
{
return n>=0 && n<= 720;
}
double calculatePakg_A(int hrs)
{
if(hrs <=50)
{
return 15.00;
}
else
{
return (hrs-50) * 2.00 + 15;
}
}
double calculatePakg_B(int hrs)
{
if(hrs <=100)
{
return 20.00;
}
else
{
return (hrs-100) * 1.50 + 20.00;
}
}
double calculatePakg_C(int hrs)
{
if(hrs <=150)
{
return 25.00;
}
else
{
return (hrs-150) * 1.00 + 25.00;
}
}
Package.txt
A a B b C c e c
Hours.txt
50 51 100 101 149 251 750 722
As I'm sure you know, you can read multiple fields from a stream:
ifstream inputFile;
char a;
inputFile.open("Packages.txt");
inputFile >> a;
cout << a << endl;
inputFile >> a;
cout << a << endl;
The reason your code doesn't work is that when control returns from getPackage(), the variable inputFile is deleted, so every time you call that function, it opens the file anew and starts reading from the beginning.
One solution is to make the input stream a static variable, so that it will not be deleted, but will maintain its state from one call to the next:
char getPackage()
{
static ifstream inputFile("Packages.txt");
char a;
inputFile >> a;
return a;
}
I think the only issue here is this.
In the function getPackage()
inputFile.open("Packages.txt");
This opens the file every time you call this function
Due to this, this function is reading the first entry (only) every time.
The same issue with getHours function.
One way out is you can read all entries from the file once into a data structure, say vector and iterate through the vector in the main function.
Another way is open the file(s) in main function and introduce a loop in main that calls these functions. Every time they are called, they would return the next entry from the file. This requires passing the opened file ifstream & as an argument to functions getHours and getPackage
I know I need to avoid global variables as much as possible but somehow I need to use certain variables in other functions.
This program is a recipe program. Adds, deletes and views recipes. Everything is working. Maybe not the best code but it works. The second part of the task is to make it so that:
THE USER INPUTS THE AMOUNT OF PEOPLE HE NEEDS TO SERVE WITH THE RECIPE. THE PROGRAM MUST CHANGE THE RECIPE QUANTITIES TO SUIT HIS NEEDS.
My plan was to make a variable called "multiplier" which is multiplied by each quantity however I don't know whether there is a better way. Unfortunately since the variables I need are in "addRecipe" I cannot possibly access them. I require "int people" and "int quan[]" so I can divide the Number of servings he wants by the number of people the recipe is for. This will give me a multiplier which I then use to multiply each NUMERICAL value within the array. The array is then outputted differently without changing the recipe.
This may not be the best plan and I have attempted it several times using parameters but I cannot seem to make it work. The code is below as is my attempts.
// Recipe.cpp : Defines the entry point for the console application.
//
int _tmain(int argc, _TCHAR* argv[])
{
return 0;
}
// Practice.cpp : Defines the entry point for the console application.
//
// 2a
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
using namespace std;
void deleteRecipe(){
DIR *dp;
struct dirent *ep;
dp = opendir ("C:\\Users\\The\\Documents\\Visual Studio 2010\\Projects\\Recipe\\Recipe");
if (dp != NULL)
{
while (ep = readdir (dp))
puts (ep->d_name);
(void) closedir (dp);
}
else
perror ("Couldn't open the directory");
cout<< "Please input the file you would like to delete from the list above: "<<endl;
string dName;
cin>>dName;
remove(dName.c_str());
cout<<"The recipe has BEEN DELETED! " <<endl;
system("pause");
}
int addRecipe(){
//PART B OF PROBLEM!
int count = 1;
string title;
string item;
int quan [100];
string units;
int people;
cout<<"What is the title of your new recipe?"<<endl;
cin.ignore();
getline(cin, title);
ofstream outFile(title+".txt", ios::out);
cout<< "How many people will this recipe serve?"<<endl;
cin>>people;
cout<< title << " - Servings: " << people << " people" <<endl;
cout<<" Please type your ingredients in the format as follows. Be to sure to input a '#'upon completion."<<endl;
while (count<1000){
cout<< "Enter Item: "<<endl;
cin.ignore();
getline(cin, item,'#');
cout<< "Enter Quantity: "<<endl;
cin>>quan[];
cout<< ("Enter units")<<endl;
getline(cin, units);
count = count++;
}
cout<< "Thank you for inputting your recipe. To view your recipe, please do nothing."<<endl;
outFile << title <<endl;
outFile<< people << " People" <<endl;
outFile<< item<<endl;
return 0;
}
int viewRecipe(){
DIR *dp;
struct dirent *ep;
dp = opendir ("C:\\Users\\The\\Documents\\Visual Studio 2010\\Projects\\Recipe\\Recipe");
if (dp != NULL)
{
while (ep = readdir (dp))
puts (ep->d_name);
(void) closedir (dp);
}
else
perror ("Couldn't open the directory");
cout<<"Please type in the name file you want to view from the list above: "<<endl;
string fileName;
string line;
cin>> fileName;
ifstream inData;
inData.open(fileName.c_str());
if (inData.is_open())
{
while ( getline (inData,line) )
{
cout << line << '\n';
}
inData.close();
int multiplier = 0;
char choice;
int newAmount;
cout<<"That was the original. If you would like to view the same recipe with a different amount of servings please press '#'."<<endl;
// PART A OF PROBLEM!
if (choice= '#'){
cout<<"How many servings would you like to adapt the recipe to?"<<endl;
cin>>newAmount;
multiplier = newAmount/ addRecipe(0, );
}
}
return 0;
}
int menu(){
int input = 0;
cout<< "1: View Recipe" <<endl;
cout<< "2: Add Recipe" <<endl;
cout<< "3: Delete Recipe" <<endl;
cout<< "Please select an option"<<endl;
cin>>input;
if (input == 1){
viewRecipe();}
if (input == 2){
addRecipe();}
if (input == 3){
deleteRecipe();}
return 0;
}
int main(){
menu();
system("pause");
cin.get();
return 0;
}
My attempt which does not work:
int addRecipe(int people, int quan[]){
int count = 1;
string title;
string item;
int quan [100];
string units;
int people;
cout<<"What is the title of your new recipe?"<<endl;
cin.ignore();
getline(cin, title);
ofstream outFile(title+".txt", ios::out);
cout<< "How many people will this recipe serve?"<<endl;
cin>>people;
cout<< title << " - Servings: " << people << " people" <<endl;
cout<<" Please type your ingredients in the format as follows. Be to sure to input a '#'upon completion."<<endl;
while (count<1000){
cout<< "Enter Item: "<<endl;
cin.ignore();
getline(cin, item,'#');
cout<< "Enter Quantity: "<<endl;
cin>>quan[];
cout<< ("Enter units")<<endl;
getline(cin, units);
count = count++;
}
cout<< "Thank you for inputting your recipe. To view your recipe, please do nothing."<<endl;
outFile << title <<endl;
outFile<< people << " People" <<endl;
outFile<< item<<endl;
return 0;
}
int viewRecipe(int multiplier){
DIR *dp;
struct dirent *ep;
dp = opendir ("C:\\Users\\The\\Documents\\Visual Studio 2010\\Projects\\Recipe\\Recipe");
if (dp != NULL)
{
while (ep = readdir (dp))
puts (ep->d_name);
(void) closedir (dp);
}
else
perror ("Couldn't open the directory");
cout<<"Please type in the name file you want to view from the list above: "<<endl;
string fileName;
string line;
cin>> fileName;
ifstream inData;
inData.open(fileName.c_str());
if (inData.is_open())
{
while ( getline (inData,line) )
{
cout << line << '\n';
}
inData.close();
int multiplier = 0;
char choice;
int newAmount;
int x = addRecipe(people, void)
cout<<"That was the original. If you would like to view the same recipe with a different amount of servings please press '#'."<<endl;
if (choice= '#'){
cout<<"How many servings would you like to adapt the recipe to?"<<endl;
cin>>newAmount;
multiplier = newAmount/ addRecipe(, );
}
Here's an idea for you (because, as you said, you shouldn't use globals unless absolutely necessary, and in your case, it's not necessary):
1.Create a class ingredient:
class ingredient {
public:
string name;
string unit;
double quantity;
ingredient(string n, string u, double q) :
name(n), unit(u), quantity(q) { }
}
2.Create a class recipe:
class recipe {
vector<ingredient> the_recipe;
public:
recipe() : the_recipe() {}
void addIngredient(const ingredient& i) {
the_recipe.push_back(i);
}
void printProportions(const int servings) {
printf("For %d servings, you need", servings);
for(int i = 0; i < the_recipe.size(); ++i) {
printf("%f %s of %s\n", the_recipe[i].quantity * servings, the_recipe[i].unit, the_recipe[i].name);
}
}
};
What do you think?
UPDATE
3.Use it in your program:
Here's an example of how you can use it (also note I've modified my struct above. In order to avoid possible confusion, I changed it to a class. They're both the same essentially in C++, with one minor difference). Anyway, here's an example:
int main() {
// create the ingredient objects
ingredient macaroni("macaroni", "grams", 50), cheese("cheese", "grams", 20);
// create a plain recipe
recipe mac_n_cheese;
// add the ingredients
mac_n_cheese.addIngredient(macaroni);
mac_n_cheese.addIngredient(cheese);
// then finally print the proportions using printProportions
mac_n_cheese.printProportions(2); // for 2 people
return 0;
}
I can think of the following ways to create and manipulate a global variable.
Just define a variable at the top of the file and use it.
int multiplier = 1; // Initialize it to a sane value.
// Later on....
// Set its value
multiplier = 10;
// Use it.
int foo = multiplier*bar;
Define a function that returns a reference to a function scoped static variable.
int& multiplier()
{
static m = 1;
return m;
}
// Later on....
// Set its value. This is an unusual syntax. But it works.
multiplier() = 10;
// Use it.
int foo = multiplier()*bar;
Im trying to lean structures and I think I am doing something wrong when I use the structure and trying to call it into a function.
#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
using namespace std;
//Structure
struct Inventory
{
int NumberPartsBin;
};
//Function Prototypes.
void choiceMenu();
void AddParts(int &);
void RemoveParts(int &);
int main()
{
char Election;
int choice;
Inventory Parts = {10};
const int Valve_Choice = 1,
Quit_Choice = 2;
I am trying to to resolve this problem with one item, but I will use arrays for 10 items.
do {
choiceMenu();
cin>> choice;
if (choice >= Valve_Choice & choice <= Quit_Choice)
{
switch(choice){
case Valve_Choice:
cout<<"Enter A for Add Parts or R to Romove Parts";
cin >> Election;
if (Election=='A')
{
AddParts(Parts);// My problem is here
}
if else (Election =='R'){
RemoveParts(Parts);}
else{
cout << "Invalid Entry. Try Again";
cin >> Election; }
break;
case Quit_Choice:
cout<<"Program Ending";
return;
else
{
cout<<"Enter a valid choice!!;
cin >> choice;
}
}
}
while (choice >= Valve_Choice & choice < Quit_Choice);
system("pause");
return 0;
// Bin Choice
void choiceMenu()
{
// We use ofstream to create and write on a text file.
ofstream outputFile;
outputFile.open("C:\\Users\\Alexander MR\\Desktop\\CompanyABCPayRoll.txt");
// The headed of the document.
outputFile << " Inventoy\n";
outputFile << " = = = = = = = = \n";
outputFile << " *Choose the part of your preference.\n";
outputFile << " 1. valves = " << Parts.NumberPartsBin << endl;
outputFile << " 11. Choose 2 to quit the Program" << endl;
outputFile.close();
}
I am not sure of my function either.
my function to add parts
void AddParts(int &Parts1)
{
int Enter1;
Parts1.NumberPartsBin = Parts1.NumberPartsBin + Enter1;
}
My function to remove parts
void RemoveParts(int &Parts2)
{
int Enter2;
Parts2.NumberPartsBin = Parts2.NumberPartsBin - Enter2;
}
Reading the question with only parts of the code formatted is quite hard. The first thing I saw was:
void RemoveParts( int &Parts2 ) {
int Enter2;
Parts2.NumberPartsBin = Parts2.NumberPartsBin - Enter2;
}
This makes no sense at all. If Parts2 is an int, then you will never be able to say Parts2.NumberPartsBin. The second thing is int Enter2;. You never give it a value, but in the next line you want to subtract it from something‽
I'm guessing (at least with this function) that you are trying to do something like this:
void RemoveParts( Inventory& inventoryItem, int amountOfParts ) { // inventoryItem is passed by reference, amountOfParts is passed by value
inventoryItem.NumberPartsBin = inventoryItem.NumberPartsBin - amountOfParts;
}
Looking at your code, I'm guessing you're quite new to all of this. I'm no guru, but please:
Capitalize class/struct names and start variable names with a lowercase. ( like parts or election)
If you want to change the value that comes into a function, pass it by reference, but if it is something like an int or a char, simply pass it by value.
p.s. it's if, else if, else and not if else which will otherwise be the next error in your code.