Okay so I've been troubleshooting an issue I have with my "process" function below. When I submit my code, I get the correct output but my loop never ends. When I try to end the loop, I get no output. I know how to end the loop if the variable is an integer but the string is throwing me for a loop. I'm new to this, and I'm sure the solution is probably right in front of my face. Thanks for the help.
int process()
{
double price = 0;
while(true)
{
int items = 0;
string order = "";
cout << "Enter your order string: ";
cin >> order;
items = findItem(order);
if (items < 0)
{
cout << order << " is invalid. Skipping it.\n";
break;
}
cout << names[items] << ": $" << fixed << setprecision(2) << prices[items] << endl;
price += prices[items];
}
cout << "Total: $" << fixed << setprecision(2) << price;
}
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
using namespace std;
const int MAXPRODUCTS = 100;
string names[MAXPRODUCTS];
double prices[MAXPRODUCTS];
string codes[MAXPRODUCTS];
int numProducts = 0;
void readConfiguration()
{
int i =0;
ifstream finput("menu.txt");
while(finput >> codes[i] >> names[i] >> prices[i])
{
i++;
numProducts = i;
}
}
//return valid index if the item is found, return -1 otherwise.
int findItem(string inputCode)
{
for(int i =0; i<numProducts; i++)
{
if(inputCode == codes[i])
return i;
}
return -1;
}
// read order string like "A1 A1 E1 E2 S1" and generate the restaurant bill.
// Output the item name and price in each line, total in the final line.
int process()
{
string order = "";
while(true)
{
int items = 0;
cout << "Enter your order string: ";
cin >> order;
items = findItem(order);
if (items < 0)
{
cout << order << " is invalid. Skipping it.\n";
continue;
}
else
cout << names[items] << ": $" << fixed << setprecision(2) << prices[items] << endl;
}
return 0;
}
int main()
{
readConfiguration();
process();
}
try to edit while(true) to while(cin >> order)
while(cin >> order)
{
int items = 0;
cout << "Enter your order string: ";
items = findItem(order);
if (items < 0)
{
cout << order << " is invalid. Skipping it.\n";
continue;
}
else
cout << names[items] << ": $" << fixed << setprecision(2) << prices[items] << endl;
}
Related
I have this program that is barely started:
#include <iostream>
#include <iomanip>
#include <ctime>
#include <string>
using namespace std;
class Grade
{
public:
string studentID;
int userChoice = 0;
int size = 0;
double* grades = new double[size]{0};
};
void ProgramGreeting(Grade &student);
void ProgramMenu(Grade& student);
string GetID(Grade& student);
int GetChoice(Grade& student);
void GetScores(Grade& student);
int main()
{
Grade student;
ProgramGreeting(student);
ProgramMenu(student);
}
// Specification C1 - Program Greeting function
void ProgramGreeting(Grade &student)
{
cout << "--------------------------------------------" << endl;
cout << "Welcome to the GPA Analyzer! " << endl;
cout << "By: Kate Rainey " << endl;
cout << "Assignment Due Date: September 25th, 2022 " << endl;
cout << "--------------------------------------------" << endl;
GetID(student);
cout << "For Student ID # " << student.studentID << endl;
}
void ProgramMenu(Grade &student)
{
cout << "--------------------------------------------" << endl;
cout << setw(25) << "Main Menu" << endl;
cout << "1. Add Grade " << endl;
cout << "2. Display All Grades " << endl;
cout << "3. Process All Grades " << endl;
cout << "4. Quit Program." << endl;
cout << "--------------------------------------------" << endl;
GetChoice(student);
}
string GetID(Grade &student)
{
cout << "Enter the student's ID: ";
cin >> student.studentID;
if (student.studentID.length() != 8) {
cout << "Student ID's contain 8 characters ";
GetID(student);
}
return student.studentID;
}
int GetChoice(Grade &student)
{
cout << "Enter your selection: ";
cin >> student.userChoice;
if (student.userChoice == 1) {
GetScores(student);
}
else if (student.userChoice == 2)
{
}
else if (student.userChoice == 2)
{
}
else if (student.userChoice == 4)
{
exit(0);
}
else
{
cout << "Please enter 1, 2, 3 or 4" << endl;
GetChoice(student);
}
}
void GetScores(Grade &student)
{
int count = 0;
double score = 0;
cout << "How many test scores would you like to enter for ID# "
<< student.studentID << "? ";
cin >> student.size;
while (count != student.size) {
cout << "Enter a grade: ";
cin >> score;
for (int i = 0; i < student.size; i++) {
student.grades[i] = score;
}
count++;
}
for (int i = 0; i < student.size; i++) {
cout << student.grades[i] << " ";
}
}
I am trying to make sure my array is recording all test scores, but when I output the array in my GetScore function, each element in the array is the same or equal to the last score I entered. For example, if I choose 3 for size and then enter three values of 99.2 86.4 90.1, all three elements will read 90.1.
Why is this happening?
Your Grade class is allocating an array of 0 double elements (which is undefined behavior), and then your GetScores() function does not reallocate that array after asking the user how many scores they will enter, so you are writing the input values to invalid memory (which is also undefined behavior).
Even if you were managing the array's memory correctly (ie, by using std::vector instead of new[]), GetScores() is also running a for loop that writes the user's latest input value into every element of the array, instead of just writing it to the next available element. That is why your final output displays only the last value entered in every element. You need to get rid of that for loop completely.
Try something more like this instead (there are several other problems with your code, but I'll leave those as separate exercises for you to figure out):
class Grade
{
public:
...
int size = 0;
double* grades = nullptr;
};
...
void GetScores(Grade &student)
{
int size = 0;
double score = 0;
cout << "How many test scores would you like to enter for ID# " << student.studentID << "? ";
cin >> size;
if (student.size != size) {
delete[] student.grades;
student.grades = new double[size]{0};
student.size = size;
}
for(int i = 0; i < size; ++i) {
cout << "Enter a grade: ";
cin >> score;
student.grades[i] = score;
}
for (int i = 0; i < size; ++i) {
cout << student.grades[i] << " ";
}
}
Alternatively:
#include <vector>
...
class Grade
{
public:
...
vector<double> grades;
};
...
void GetScores(Grade &student)
{
size_t size = 0;
double score = 0;
cout << "How many test scores would you like to enter for ID# " << student.studentID << "? ";
cin >> size;
student.grades.resize(size);
for (size_t i = 0; i < size; ++i) {
cout << "Enter a grade: ";
cin >> score;
student.grades[i] = score;
}
/* alternatively:
student.grades.clear();
for (size_t i = 0; i < size; ++i) {
cout << "Enter a grade: ";
cin >> score;
student.grades.push_back(score);
}
*/
for (size_t i = 0; i < size; ++i) {
cout << student.grades[i] << " ";
}
}
I removed my for loop from my while loop.
void GetScores(Grade &student)
{
int count = 0;
double score = 0;
cout << "How many test scores would you like to enter for ID# "
<< student.studentID << "? ";
cin >> student.size;
while (count != student.size) {
cout << "Enter a grade: ";
cin >> score;
student.grades[count] = score;
count++;
}
for (int j = 0; j < student.size; j++) {
cout << student.grades[j] << " ";
}
}
This is my code at the moment. It is a lottery game and I get user input for 7 numbers and do not allow duplicates (same goes with the random generated). I need to display the user's numbers and the winning random numbers at the end of the main next to LOTTO RESULTS and WINNING NUMBERS.
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <string>
using namespace std;
void getLottoPicks(int userNums[], int size);
void genWinNums(int winNums[], int size);
int main()
{
const int size = 7;
int UserTicket[size];
int WinningNums[size];
char selection;
string name;
do
{
cout << "LITTLETON CITY LOTTO MODEL: " << endl;
cout << "---------------------------" << endl;
cout << "1) Play Lotto" << endl;
cout << "q) Quit Program" << endl;
cout << "Please make a selection : " << endl;
cin >> selection;
if (selection == '1')
{
cout << "Please enter your name: " << endl;
cin.ignore();
getline(cin, name);
getLottoPicks(UserTicket, size);
genWinNums(WinningNums, size);
cout << name << "'s LOTTO RESULTS" << endl;
cout << "----------------------" << endl;
cout << "WINNING TICKET NUMBERS : " << endl;
cout << name << "'s TICKET : " << endl;
}
else if (selection == 'q')
{
cout << "You have chosen to quit the program. Thank you for using!" << endl;
}
else
{
cout << "Invalid selection. Please try again." << endl;
}
} while (selection != 'q');
return 0;
}
void getLottoPicks(int userNums[], int size)
{
for (int times = 0; times < size; times++)
{
int input;
cout << "selection #" << times + 1 << ": " << endl;
cin >> input;
bool isNotDuplicate = true;
for (int i = 0; i < times; i++)
{
if (userNums[i] == input)
{
isNotDuplicate = false;
}
}
if (isNotDuplicate == true)
{
userNums[times] = input;
}
else
{
cout << "You already picked this number. Please enter a different number: " <<
endl;
times--;
}
}
}
void genWinNums(int winNums[], int size)
{
srand((unsigned int)time(NULL));
for (int times = 0; times < size; times++)
{
int i;
bool isNotDuplicate = true;
while (isNotDuplicate)
{
isNotDuplicate = false;
i = 1 + rand() % 40;
for (int j = 0; j < times; j++)
{
if (i == winNums[j])
{
isNotDuplicate = true;
}
}
}
winNums[times] = i;
}
}
It seems you might be new to programming so here you go, your working program:
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <string>
using namespace std;
void getLottoPicks(int userNums[], int size);
void genWinNums(int winNums[], int size);
int main()
{
const int size = 7;
int UserTicket[size];
int WinningNums[size];
char selection;
string name;
do
{
cout << "LITTLETON CITY LOTTO MODEL: " << endl;
cout << "---------------------------" << endl;
cout << "1) Play Lotto" << endl;
cout << "q) Quit Program" << endl;
cout << "Please make a selection : " << endl;
cin >> selection;
if (selection == '1')
{
cout << "Please enter your name: " << endl;
cin.ignore();
getline(cin, name);
getLottoPicks(UserTicket, size);
genWinNums(WinningNums, size);
cout << name << "'s LOTTO RESULTS" << endl;
cout << "----------------------" << endl;
cout << "WINNING TICKET NUMBERS : " << endl;
for(int i = 0; i < size; i++){
cout << WinningNums[i] << " ";
}
cout << endl;
cout << name << "'s TICKET : " << endl;
for(int i = 0; i < size; i++){
cout << UserTicket[i] << " ";
}
cout << endl;
}
else if (selection == 'q')
{
cout << "You have chosen to quit the program. Thank you for using!" << endl;
}
else
{
cout << "Invalid selection. Please try again." << endl;
}
} while (selection != 'q');
return 0;
}
void getLottoPicks(int userNums[], int size)
{
for (int times = 0; times < size; times++)
{
int input;
cout << "selection #" << times + 1 << ": " << endl;
cin >> input;
bool isNotDuplicate = true;
for (int i = 0; i < times; i++)
{
if (userNums[i] == input)
{
isNotDuplicate = false;
}
}
if (isNotDuplicate == true)
{
userNums[times] = input;
}
else
{
cout << "You already picked this number. Please enter a different number: " <<
endl;
times--;
}
}
}
void genWinNums(int winNums[], int size)
{
srand((unsigned int)time(NULL));
for (int times = 0; times < size; times++)
{
int i;
bool isNotDuplicate = true;
while (isNotDuplicate)
{
isNotDuplicate = false;
i = 1 + rand() % 40;
for (int j = 0; j < times; j++)
{
if (i == winNums[j])
{
isNotDuplicate = true;
}
}
}
winNums[times] = i;
}
}
As you can see, it is pretty easy to loop through an array. Maybe have a look at this for more info on arrays.
Most of the examples show "classic" C++, instead of the more modern variants.
So here's my take on your code :
#include <algorithm>
#include <array>
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <string>
// compile time constant, in many C++ examples this is done with a #define/MACRO
constexpr int number_of_lotto_numbers = 7;
constexpr char play_lotto_char = '1';
constexpr char quit_lotto_char = 'q';
// use std::array instead of int values[]; since this has automatic bound checking!
// no reading/writing beyond array limits is allowed
// I use, using here to make code a bit more readable further down the line
// it lets code show intent instead of implementation
using lotto_numbers_t = std::array<int, number_of_lotto_numbers>;
// do not return arrays by passing arguments, just return an array
// don't worry about this making extra (class) copies c++ knows how to optimize this
lotto_numbers_t get_lotto_picks()
{
lotto_numbers_t lotto_numbers;
auto lotto_numbers_entered{ 0 };
while ( lotto_numbers_entered < number_of_lotto_numbers )
{
int input{ 0 };
std::cout << "selection #" << lotto_numbers_entered + 1 << ": " << std::endl;
std::cin >> input;
// use std::find for finding items in collections, if it finds the end of a collection then
// the value is not found.
if (std::find(lotto_numbers.begin(), lotto_numbers.end(), input) == lotto_numbers.end())
{
// lotto number not found so add it
lotto_numbers[lotto_numbers_entered] = input;
lotto_numbers_entered++;
}
else
{
// lotto number already in array so do not add it but give a message
std::cout << "You already entered this number, try another number" << std::endl;
}
}
return lotto_numbers;
}
lotto_numbers_t generate_winning_numbers()
{
lotto_numbers_t lotto_numbers;
auto lotto_numbers_generated{ 0 };
std::srand((unsigned int)time(NULL));
do
{
int new_number = (std::rand() % 40) + 1;
if (std::find(lotto_numbers.begin(), lotto_numbers.end(), new_number) == lotto_numbers.end())
{
// number not yet found
lotto_numbers[lotto_numbers_generated] = new_number;
lotto_numbers_generated++;
}
} while (lotto_numbers_generated < number_of_lotto_numbers);
return lotto_numbers;
}
void play_lotto()
{
char selection{ 0 }; // always initialize variables!
std::string name;
do
{
std::cout << "LITTLETON CITY LOTTO MODEL: " << std::endl;
std::cout << "---------------------------" << std::endl;
std::cout << "1) Play Lotto" << std::endl;
std::cout << "q) Quit Program" << std::endl;
std::cout << "Please make a selection : " << std::endl;
std::cin >> selection;
if (selection == play_lotto_char)
{
std::cout << "Please enter your name: " << std::endl;
std::cin.ignore();
std::getline(std::cin, name);
auto picked_numbers = get_lotto_picks();
auto winning_numbers = generate_winning_numbers();
std::cout << name << "'s LOTTO RESULTS" << std::endl;
std::cout << "----------------------" << std::endl;
std::cout << "WINNING TICKET NUMBERS : " << std::endl;
for (const auto number : winning_numbers)
{
std::cout << number << " ";
}
std::cout << std::endl;
std::cout << name << "'s TICKET : " << std::endl;
for (const auto number : picked_numbers)
{
std::cout << number << " ";
}
std::cout << std::endl;
if (picked_numbers == winning_numbers)
{
std::cout << "you have won!" << std::endl;
}
}
else if (selection == quit_lotto_char)
{
std::cout << "You have chosen to quit the program. Thank you for using!" << std::endl;
}
else
{
std::cout << "Invalid selection. Please try again." << std::endl;
}
} while (selection != quit_lotto_char);
}
Don't hesitate to ask questions on this code if you have any :)
I am tasked with storing a binary tree within a vector. Within each node is stored an int ID, int Age, and a string name.
The nodes are stored and organized within the vector by ID.
When storing the binary tree within a vector, I am using the algorithm 2i and 2i+1 to dictate a node's left and right child respectively.
I have managed to create an insert method that I believe satisfies these conditions, however for some reason, when attempting to print the values of my vector, I appear to get negative values. For this particular example, I insert the following values
50 21 Tim
75 22 Steve
30 40 Eric
20 35 Mary
100 60 Judy
After inserting these four values, I attempt to use my find() method to find Eric, in which my program returns "Not Found!"
I run my report() function to find that all the values stored within my vector are large negative valued IDs.
Is there a particular reason for this? Find()
Report()
Here is my code.
#include "BinaryTree.h"
#include <string>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int index = 0;
struct Node
{
int ID;
int age;
string name;
Node()
{
}
Node(int id, int Age, string nm)
{
this->ID = id;
this->age = Age;
this->name = nm;
}
};
vector<Node> binaryTree(30);
BST::BST()
{
}
void BST::start()
{
int choice;
cout << "What would you like to do?" << endl;
cout << "1. Add a node to the tree" << endl;
cout << "2. Delete a node from the tree" << endl;
cout << "3. Find a node in the tree" << endl;
cout << "4. Report the contents of the tree" << endl;
cout << "5. Exit program" << endl;
cin >> choice;
if (choice == 1)
{
insert();
}
if (choice == 2)
{
Delete();
}
if (choice == 3)
{
find();
}
if (choice == 4)
{
report();
}
}
void BST::insert()
{
int ID;
int AGE;
string NAME;
int root = 1;
bool success = false;
cout << "Please enter the ID number, age and name:" << endl;
do
{
cin >> ID >> AGE >> NAME;
} while (ID < 0);
Node *tree = new Node(ID, AGE, NAME);
if (index = 0)
{
binaryTree[1] = *tree;
}
if (index > 0)
{
do
{
if (tree->ID > binaryTree.at(root).ID)
{
root = 2 * root + 1;
}
if (tree->ID < binaryTree.at(root).ID)
{
root = 2 * root;
}
if (binaryTree.at(root).ID == NULL)
{
binaryTree.at(root) = *tree;
success = true;
}
} while (!success);
}
index++;
delete tree;
start();
}
void BST::Delete()
{
int input_id;
cout << "What is the ID of the person to be deleted" << endl;
cin >> input_id;
for (unsigned int i = 0; i < binaryTree.size(); i++)
{
if (input_id == binaryTree.at(i).ID)
binaryTree.erase(binaryTree.begin() + i);
}
cout << " " << endl;
start();
}
void BST::find()
{
int key;
bool found = 0;
cout << "What's the ID?" << endl;
cout << " " << endl;
cin >> key;
for (unsigned int i = 0; i < binaryTree.size(); i++)
{
if (binaryTree.at(i).ID == key)
{
cout << "The ID is " << binaryTree.at(i).ID << endl;
cout << "The age ID " << binaryTree.at(i).age << endl;
cout << "The name is " <<binaryTree.at(i).name << endl;
cout << " " << endl;
found = true;
}
if (found == false)
{
cout << "Not found." << endl;
cout << "" << endl;
break;
}
}
start();
}
void BST::report()
{
cout << "The contents of the tree are" << endl;
cout << " " << endl;
for (unsigned int i = 0; i < binaryTree.size(); i++)
{
int level = 0;
if (i == 0) level = 0;
if (i == 1 || i == 2) level = 1;
if (i >= 3 && i <= 6) level = 2;
if (i >= 7 && i <= 14) level = 3;
//TODO complete list
cout << binaryTree.at(i).ID << " " << binaryTree.at(i).age << " " << &binaryTree.at(i).name << " " << level << endl;
}
}
Would appreciate the suggestions/help!
Thanks!
I think issues is with indexing here
In insert() you created binary tree with root at index in but in report() function you started output from index 0. I have no idea what binaryTree.at(int) do.
But in find() your error is due to the fact that you have included if(found == 0) inside the loop. This means that it will break the loop if 1st element of tree is not the element you are searching. Use this code instead
void BST::find()
{
int key;
bool found = 0;
cout << "What's the ID?" << endl;
cout << " " << endl;
cin >> key;
for (unsigned int i = 0; i < binaryTree.size(); i++)
{
if (binaryTree.at(i).ID == key)
{
cout << "The ID is " << binaryTree.at(i).ID << endl;
cout << "The age ID " << binaryTree.at(i).age << endl;
cout << "The name is " <<binaryTree.at(i).name << endl;
cout << " " << endl;
found = true;
}
}
if (found == false)
{
cout << "Not found." << endl;
cout << "" << endl;
}
start();
}
I get an error saying: use of undeclared identifier 'again'.
I am trying to go from int main to void again and back after getting an answer.
Please explain to me why it won't work also. Thanks.
Here is my full code:
#include <iostream>
#include <vector>
#include <iomanip>
#include <algorithm>
#include <string>
using namespace std;
{
string answer;
cout << "Would you like to enter another set of data? Y or N?" << endl;
cin << answer;
string yes = "Yes";
string no = "No";
if(a == yes)
{
main();
}
}
int main()
{
cout << "Kaitlin Stevers" << endl;
cout << "Exercise 11 - Vectors" << endl;
cout << "November 12, 2016" <<endl;
cout << endl;
cout << endl;
int size;
cout << " How many numbers would you like the vector to hold? " << endl;
cin >> size;
vector<int> numbers;
int bnumbers;
for (int count = 0; count < size; count++)
{
cout << "Enter a number: " << endl;
cin >> bnumbers;
numbers.push_back(bnumbers); // Adds an element to numbers
}
//display the numbers stored in order
cout << "The numbers in order are: " << endl;
for(int bcount = 0; bcount < size; bcount++)
{
cout << numbers[bcount] << " ";
}
cout << endl;
//display the numbers stored reversed
cout << "Here are the numbers in reverse order: " << endl;
reverse(numbers.begin(), numbers.end());
for(int rcount = 0; rcount < size; rcount++)
{
cout << numbers[rcount] << " ";
}
cout << endl;
again();
return 0;
}
void again()
}
You need to declare your fonction "again" before calling it :
#include <iostream>
#include <vector>
#include <iomanip>
#include <algorithm>
#include <string>
using namespace std;
void again();
int main()
{
cout << "Kaitlin Stevers" << endl;
cout << "Exercise 11 - Vectors" << endl;
cout << "November 12, 2016" <<endl;
cout << endl;
cout << endl;
int size;
cout << " How many numbers would you like the vector to hold? " << endl;
cin >> size;
vector<int> numbers;
int bnumbers;
for (int count = 0; count < size; count++)
{
cout << "Enter a number: " << endl;
cin >> bnumbers;
numbers.push_back(bnumbers); // Adds an element to numbers
}
//display the numbers stored in order
cout << "The numbers in order are: " << endl;
for(int bcount = 0; bcount < size; bcount++)
{
cout << numbers[bcount] << " ";
}
cout << endl;
//display the numbers stored reversed
cout << "Here are the numbers in reverse order: " << endl;
reverse(numbers.begin(), numbers.end());
for(int rcount = 0; rcount < size; rcount++)
{
cout << numbers[rcount] << " ";
}
cout << endl;
again();
return 0;
}
void again()
{
string answer;
cout << "Would you like to enter another set of data? Y or N?" << endl;
cin >> answer;
string yes = "Yes";
string no = "No";
if(answer == yes)
{
main();
}
}
However, it's a strange things to use recursivity for what you want to do and to call main func multiple times (which is by definition, main entry of a program). In my opinion, you should call in your main function another function named like askInformation which uses a loop with a test case to know if user wants to add informations or not.
Right now my problem seems to be focused on the saveFile function.
I will post the entire program here, so dont be ired when see a whole bunch of code... just look at the saveFile function at the bottom... I am posting all the code JUST IN CASE it will help you help me solve my problem.
Now for defining the apparent problem to you all: I can edit the file throughout the life of the console app with the updateSale function as I run it, but when I use the saveFile function and put in 'y' to save, the differences that are visible after using the updateSales function DO NOT get saved to the actual sales file called "salespeople.txt" and I do not understand why.
this is what the salespeople.txt looks like:
Schrute 25000
Halpert 20000
Vance 19000
Hudson 17995.5
Bernard 14501.5
now here is the program:
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
//variables--------------------------------------------------------
int lineCount = 0;
//prototypes-------------------------------------------------------
int getIndexLargest(string[], double[]);
void displaySalesPeople(string[], double[]);
bool readSalesFile(string[], double[]);
void updateSales(string[], double[]);
int saveFile(string, string[], double[], int);
int main()
{
string fileName;
int arrayLength;
ifstream readSales;
string salesPersonName[5];
double saleAmount[5];
bool flag = false;
int options;
do
{
cout << "1) Open sales person file. "<< endl;
cout << "2) Display sales person information. "<< endl;
cout << "3) Update sales. " << endl;
cout << "4) Get best sales person. " << endl;
cout << "5) Exit. " << endl;
cout << "Please enter a number 1-5 to select an option." <<endl;
cin >> options;
if(options == 1)
{
flag = readSalesFile(salesPersonName, saleAmount);
}
else if(options == 2)
{
if(flag == false)
{
cout << "Please open sales file before selecting this option. Try again" << endl;
}
else
displaySalesPeople(salesPersonName, saleAmount);
}
else if(options == 3)
{
if(flag == false)
{
cout << "Please open sales file before selecting this option. Try again" << endl;
}
else
updateSales(salesPersonName, saleAmount);
}
else if(options == 4)
{
if(flag == false)
{
cout << "Please open sales file before selecting this option. Try again" << endl;
}
getIndexLargest(salesPersonName, saleAmount);
}
else if(options == 5)
{
char choice;
cout << "Enter character y to save... anything else will exit without saving: " << endl;
cin >> choice;
if(choice == 'y')
{
saveFile(fileName, salesPersonName, saleAmount, arrayLength);
cout << "File saved. " << endl;
}
else
{
cout << "closing program" << endl;
}
}
}
while(options != 5);
return 0;
}
//functions---------------------------------
bool readSalesFile(string salesPersonName[], double saleAmount[])
{
bool flag = false;
ifstream readSales;
string fileName;
cout << "Please enter the path to your sales people file: ";
getline(cin, fileName);
readSales.open(fileName.c_str());
while(readSales.fail())
{
cout << "Failed. Please enter the path to your sales file again: ";
getline(cin, fileName);
readSales.open(fileName.c_str());
}
if(readSales.good())
{
flag = true;
cout << lineCount;
string name = " ";
double amount =0.00;
int i = 0;
while(!readSales.eof())
{
readSales >> name;
readSales >> amount;
salesPersonName[i] = name;
saleAmount[i] = amount;
i++;
}
for(i = 0; i < 5; i++)
{
cout << "Sales person name: " << salesPersonName[i] << endl;
cout << "Sale amount: $" << saleAmount[i] << endl;
}
readSales.close();
}
readSales.close();
return flag;
}
void displaySalesPeople(string salesPersonName[], double saleAmount[])
{
for(int i = 0; i < 5; i++)
{
cout << "Sales person name: " << salesPersonName[i] << endl;
cout << "Sale amount: $" << saleAmount[i] << endl;
}
}
void updateSales(string salesPersonName[], double saleAmount[])
{
bool flag = false;
string findName;
double moneyAmount;
cout << "Enter name of sales person you want to modify: " << endl;
cin >> findName;
for(int i = 0; i < 5; i++)
{
if(findName == salesPersonName[i])
{
cout << "Enter the sale amount you would like to modify: " << endl;
cin >> moneyAmount;
saleAmount[i] += moneyAmount;
cout << saleAmount[i] << endl;
flag = true;
}
}
if(flag == false)
{
cout << " name not found" << endl;
}
}
int getIndexLargest(string salesPersonName[], double saleAmount[])
{
ifstream readSales;
while(!readSales.eof())
{
double largestSale = 0.00;
string largestSalesPerson;
int i = 0;
lineCount++;
readSales >> salesPersonName[i];
readSales >> saleAmount[i];
if(saleAmount[i] > largestSale)
{
largestSale = saleAmount[i];
largestSalesPerson = salesPersonName[i];
}
cout << "Best sales person : "<< largestSalesPerson << " $" <<setprecision(2)<<fixed<< largestSale << endl;
}
}
int saveFile(string fileName, string salesPersonName[], double saleAmount[], int arrayLength)
{
ofstream saveFile(fileName.c_str());
saveFile.open(fileName.c_str());
for(int i = 0; i < 5; i++)
{
saveFile << salesPersonName[i] << " " << saleAmount[i] << endl;
}
saveFile.close();
return 0;
}
You are trying t open your file twice:
ofstream saveFile(fileName.c_str()); // this opens the file
saveFile.open(fileName.c_str()); // so does this
That will put the file in an error state so no writing will happen.
Just do this:
ofstream saveFile(fileName.c_str()); // this opens the file
And that should work.
Or else you can do this:
ofstream saveFile; // this does not open the file
saveFile.open(fileName.c_str()); // but this does
And that should work too.