I am trying to open the txt file I made for the rest of my code to successfully run. I am using c++ and xcode is the environment. When I run my code, I get this:
error in opening studentScore8.txt
And below that is the correct formatting for the table but weird numbers are there. I am confident that the location for the file is correct, and I am not seeing any issues in my code besides
printGrade(oneScore, average);
in the main function, which xcode is saying that the parameters oneScore and average are not initialized, but I thought I already did that above.
Does anyone know what the issue could be? This is a lab for my comp sci class, and my teacher doesn't seem to know what the issue is either. I am thinking it has something to do with xcode or my computer itself, but I am not sure. The entire code is below.
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
#define inFile "/Users/spacecowboy/Desktop/cis/cis/lab 8/studentScore8.txt"
const int MAX_SIZE = 4;
void readStuData (ifstream& rss, int scores[], int id[], int& count, bool& tooMany);
float mean(int scores[], int count);
void printTable(int scores[], int id[], int count);
void printGrade(int oneScore, float average);
int main() {
ifstream rss;
// void printTable(scores, id, count);
// float mean(int scores, int count);
float average;
bool tooMany;
int scores[MAX_SIZE];
int oneScore;
int id[MAX_SIZE];
int count;
rss.open("studentScore8.txt");
if (rss.fail()){
cout << "error in opening studentScore8.txt" << endl;
}
readStuData(rss, scores, id, count, tooMany);
mean(scores, count);
printGrade(oneScore, average);
printTable(scores, id, count);
rss.close();
return 0;
}
void readStuData(ifstream& rss, int scores[], int id[], int& count,bool& tooMany){
int stuID;
int stuScore;
int i;
for (i = 0; i < MAX_SIZE; ++i) {
rss >> stuID;
rss >> stuScore;
id[i] = stuID;
scores[i] = stuScore;
++count;
}
if (count > MAX_SIZE){
tooMany = true;
}
else {
tooMany = false;
}
}
float mean(int scores[], int count)
{
float sum = 0;
int i;
for (i = 0; i < count; ++i) {
sum = sum + scores[i];
}
return sum / count;
}
void printGrade(int oneScore, float average){
ifstream rss;
rss >> oneScore;
if (((oneScore >= average -10) && (oneScore <= average + 10))) {
cout << "Satisfactory";
}
else if (oneScore == average + 10){
cout << "Satisfactory";
}
else if (oneScore > average + 10){
cout << "Outstanding";
}
else {
cout << "Unsatisfactory";
}
}
void printTable(int scores[], int id[], int count){
int i;
cout << endl;
cout << setw(10) << left << "Student ID" << "|";
cout << setw(6) << right << "Score" << "|" ;
cout << setw(14) << left << "Grade" << endl;
cout << setfill('-') << setw(30) << "" << endl;
for(i = 0; i < MAX_SIZE; ++i){
cout << left << setw(10) << id[i] << "|";
cout << left << " ";
cout << setw(2) << scores[i];
cout << right << " " << "|";
printGrade(scores[i], mean(scores, count));
cout << endl;
}
cout<< setfill('-') << setw(30) << "" << endl;
}
Related
I wrote a code to manage a coffee machine,
I have a function findC that finds the cheapest capsule in the capsule array
a different function of mine findVP that is supposed to use the findC function's output as variables. however, when I pass the variables mp, ind = findC(prices_copy, quantities_copy, SIZE);
and print them it passes them as 0;
but the 2nd cout : cout << findC(prices_copy, quantities_copy, SIZE); prints the correct output.
why is this ? and how can I pass the output of the function to another
/******************************************************************************
Online C++ Compiler.
Code, Compile, Run and Debug C++ program online.
Write your code in this editor and press "Run" button to compile and execute it.
*******************************************************************************/
// Example program
#include <iostream>
#include <string>
#include <bits/stdc++.h>
using namespace std;
#define SLEEVE 10
#define SIZE 10
#define N 5
#define BUDGET 70
//int CapsuleKind[10] = {"JOE","MAC","NES","jamaica","brazil","columbia","MOJO","CLUB","JHON","COF"};
float findMostExpensiveCapsule( float prices[], int size ) // 1
{
float max = prices[0];
int count = 0;
for(int i = 1; i < size; i++)
{
if (prices[i] > max)
{
max = prices[i];
}
}
cout << "The maximum price " << max << " is found on indexes: " ;
for (int i = 0; i < size; i++)
{
if (prices[i] == max)
{
cout << i << " ";
count++;
}
}
cout << endl;
cout << "The maximum number appears " << count << " times." << endl;
return max;
}
int findStrongestCapsuleInStock( int quantities[], int size, int sleeve ) // 2
{
return 0;
}
void SellCapsules( int quantities[], int Qty, int index) // 10
{
quantities[index] = quantities[index] - Qty;
cout << "SOLD " << Qty << " capsules to the Customer, the total now is: " << quantities[index] << endl;
}
float findC( float prices[],int quantities[], int size ) // 9
{
float min = 99999;
int count = 0;
float index=0;
//sort(prices, arr + n);
for(int i = 0; i < size; i++)
{
if (quantities[i] >= SLEEVE)
{
if(prices[i] < min){
min = prices[i];
index= i;
}
else continue;
}
}
cout <<"the minimum price is : " << min << " ---- the index is : " << index << endl;
return min, index;
}
void findCheapestSleeve( float prices[],int quantities[], int size )
{
float min = prices[0];
int count = 0;
int index=0;
for(int i = 0; i < size; i++)
{
if (prices[i] < min)
{
if(quantities[i] > SLEEVE){
min = prices[i];
index= i;
}
else continue;
}
}
cout <<"the minimum price is : " << min << " ---- the index is : " << index << endl;
}
void showAllCapsulesInStock( int quantities[], float prices[], int size, int sleeve) // 3
{
for (int i = 0; i < size; i++)
{
cout << "capsule kind: " << i << " ---- sleeves available : " << (quantities[i]/sleeve) << " ---- price(for 1 sleeve): " << (prices[i]*sleeve)<< endl;
}
}
float findVP( float prices[], int quantities[], int size, float nis, int sleeve ) //4
{
float mp=0;
float ind =0;
float prices_copy[size];
int quantities_copy[size];
for(int i=0; i<size; i++){
prices_copy[i] = prices[i];
quantities_copy[i] = quantities[i];
}
mp, ind = findC(prices_copy, quantities_copy, SIZE);
cout << "The lowest price sleeve is: " << mp * 10 << " --- the capsule kind is: " << ind <<endl;
cout << findC(prices_copy, quantities_copy, SIZE);
}
void findValueForMoneyPackage( float prices[], int quantities[], int size, float nis, int sleeve )
{
int sleeve_num[size];
float sleeve_price[size];
float min=0;
int index = 0;
int counter=0;
float quant = 0;
for (int i=0; i < size; i++)
{
sleeve_num[i] = (quantities[i]/sleeve);
sleeve_price[i] = (prices[i] * sleeve);
}
//min, quant = findCheapestSleeve(sleeve_price, quantities, 10);
cout << "the cheapest sleeve costs : " << min << " and its of kind :" << quant << endl;
}
void addMoreCapsules( int quantities[], int size ) // 5
{
char answer;
int plus;
for (int i = 0; i < size; i++)
{
cout << "do you want to add capsules to capsule kind " << i << "? (Y/N) " << endl;
cin >> answer;
if (answer == 'Y')
{
cout << "How many capsules do you want to add (inter a number) " << endl;
cin >> plus;
if (plus > 0)
{
quantities[i] = quantities[i] + plus;
cout << "Added " << plus << " capsules to the inventory, the total now is: " << quantities[i] << endl;
}
}
else
{
continue;
}
}
}
// Driver Code
int main()
{
bool flag = false;
int option;
float prices[] = { 1.2, 2.2, 2.5, 1.7, 2.2, 3, 2.8, 2.5, 2.9, 3.7 };
int quantities[] = { 14, 22, 25, 13, 22, 33, 50, 60, 33, 25 };
while (flag != true)
{
cout << "Please choose an option , has to be a number 1-6" << endl;
cin >> option;
if (option == 1)
{
findMostExpensiveCapsule(prices,SIZE);
}
else if ( option == 3)
{
showAllCapsulesInStock(quantities, prices, SIZE, 10);
}
else if (option == 4){
findVP(prices, quantities, SIZE, BUDGET, SLEEVE);
}
else if(option == 5){
addMoreCapsules(quantities,SIZE);
}
else if(option == 9){
findC(prices, quantities, SIZE);
}
else
{
flag = true;
}
}
cout << "GoodBye!" << endl;
return 0;
}
This
return min, index;
doesn't do what you think it does. You obviously think it's going to return two values. But actually it just returns index.
This
mp, ind = findC(prices_copy, quantities_copy, SIZE);
doesn't do what you think it does. You obviously think it's going to assign the two returned values from findC to the variables mp and ind. But actually it's going to return the single value returned by findC to the variable ind and ignore mp.
If you want to know precisely what these constructs do then look up the comma operator, but I guess the moral of the story is that just because you can get some plausible looking code to compile it doesn't mean that it's going to do what you expected it to do.
So the real question is how to return two values from a function in C++. There are actually several possible approaches. Here's a question that reviews some of them, Returning multiple values from a C++ function.
Having trouble storing strings into an array. I tried a multi-dimensional char array but it didn't work. I would ideally like a multi-dimensional string array but every time I try I get the error
cannot convert std::string (*)[100] {aka std::basic_string<char> (*)[100]} to std::string*
Don't even understand what that means. I tried printing the array in my function input_new_student which is where I store the string just to test it, and no luck. The same thing is happening to all my arrays. I've looked it up but I feel like im overlooking something very simple, please help.
#include <iostream>
#include <iomanip>
#include <string>
#include <cstdlib>
#include <ctime>
void print_menu();
int get_selection();
std::string get_Name();
float get_GPA();
int get_Year();
void input_new_student(std::string student_names[], float student_GPA[], int student_start_year[], int index, int ramapo_id[]);
void print_all(std::string student_names[], float student_GPA[], int student_start_year[], int index, int size, int ramapo_id[]);
void print_by_year(std::string student_names[], float student_GPA[], int student_start_year[], int index, int size);
void print_statistics(std::string student_names[], float student_GPA[], int student_start_year[], int index, int size, float sum);
using namespace std;
int main()
{
std::string student_names[100];
float student_GPA[100];
int student_start_year[100];
int ramapo_id[100];
int userChoice;
int index = 0;
int size = 0;
float sum = 0.0;
do
{
print_menu();
userChoice = get_selection();
if (userChoice == 1)
{
input_new_student(student_names, student_GPA, student_start_year, index, ramapo_id);
index++;
}
if (userChoice == 2)
{
print_all(student_names, student_GPA, student_start_year, index, size, ramapo_id);
}
if (userChoice == 3)
{
print_by_year(student_names, student_GPA, student_start_year, index, size);
}
if (userChoice == 4)
{
print_statistics(student_names, student_GPA, student_start_year, index, size, sum);
}
if (userChoice == 5)
{
return 0;
}
} while(userChoice > 0 && userChoice < 4);
return 0;
}
void print_menu()
{
cout << "Please pick from the following menu " << endl;
cout << "1. Add a new student " << endl;
cout << "2. Print all students " << endl;
cout << "3. Print students by year " << endl;
cout << "4. Print student statistics " << endl;
cout << "5. Quit" << endl;
}
int get_selection()
{
int userChoice;
cin >> userChoice;
while (userChoice > 4 || userChoice < 1)
{
cout << "Error: Invalid input, please try again: ";
cin >> userChoice;
}
return userChoice;
}
string get_Name()
{
std::string student_name;
cout << "Please enter the student's name: ";
cin >> student_name;
return student_name;
}
float get_GPA()
{
float student_GPA;
cout << "Please enter the GPA: ";
cin >> student_GPA;
return student_GPA;
}
int get_Year()
{
int student_year;
cout << "Please enter the start Year: ";
cin >> student_year;
return student_year;
}
void input_new_student(std::string student_names[], float student_GPA[], int student_start_year[], int index, int ramapo_id[])
{
//information generation
srand((unsigned)time(0));
int random_integer = rand();
ramapo_id[index] = random_integer;
//information acquisition
student_names[index] = get_Name();
student_GPA[index] = get_GPA();
student_start_year[index] = get_Year();
}
void print_all(std::string student_names[], float student_GPA[], int student_start_year[], int index, int size, int ramapo_id[])
{
for (int i = 0; i < size; i++) {
cout << student_names[i] << " - " << ramapo_id[i] << endl;
}
}
void print_by_year(std::string student_names[], float student_GPA[], int student_start_year[], int index, int size)
{
int student_year_identifier;
cout << "Which year would you like to display?: ";
cin >> student_year_identifier;
for (int i = 0; i < size; i++)
{
if (student_year_identifier == student_start_year[i])
{
cout << "There were " << index << "students in that year" << endl;
}
else {
cout << "There were no students in that year" << endl;
}
}
}
void print_statistics(std::string student_names[], float student_GPA[], int student_start_year[], int index, int size, float sum)
{
cout << "Total: " << index << endl;
float avg = 0.0;
for (int i = 0; i < size; ++i)
{
sum += student_GPA[i];
}
avg = ((float)sum)/size;
cout << "GPA: " << avg << endl;
}
I recommend you have a container of structures rather than multiple containers:
struct Student_Info
{
std::string name;
double gpa;
unsigned int starting_year;
}
typedef std::vector<Student_Info> Student_Info_Container;
Student_Info_Container database;
// You could also have an array of student information:
static const size_t MAXIMUM_STUDENTS = 32U;
Student_Info_Container student_information[MAXIMUM_STUDENTS];
Placing the information into a structure support encapsulation and makes the program more efficient.
With parallel arrays, there is a possibility of synchronization issues. For example, the GPA for student 3 may be at index 4 of the array.
If you are restricted to arrays, you would only need to pass 2 parameters to your functions, the array and the capacity of the array.
There are few issues with your code, e.g.:
Your code is difficult to debug because you are using infinite while loops while taking input (e.g. in main and get_selection function).
How would you know if your code is working? At least, print something which indicates that your code is working, like cout << "Student added suuccessfully"; in input_new_student function.
I made these above mentioned changes and you can see that (at least) your code is working for option 1 at http://ideone.com/D5x8Eh
PS: I didn't get that compilation error, you should mention the compiler and flags you are using.
So as an update, the reason I wasn't able to print my array was begin I was not incrementing in my for loop. Thanks to #milesbudnek , #dreschjerm. I was able to see that my code was actually printing by adding the messages, this was prior to the suggestions, but thanks for the suggestion. Here is the code as it is now. Currently I just need to find a way to find values in the array (which I will search for) and create the multi-dimensional array for the strings.
#include <iostream>
#include <iomanip>
#include <string>
#include <cstdlib>
#include <ctime>
void print_menu();
int get_selection();
std::string get_Name();
float get_GPA();
int get_Year();
void input_new_student(std::string student_names[], float student_GPA[], int student_start_year[], int index, int ramapo_id[]);
void print_all(std::string student_names[], float student_GPA[], int student_start_year[], int index, int size, int ramapo_id[]);
void print_by_year(std::string student_names[], float student_GPA[], int student_start_year[], int index, int size);
void print_statistics(std::string student_names[], float student_GPA[], int student_start_year[], int index, int size, float sum);
using namespace std;
int main()
{
std::string student_names[100];
float student_GPA[100];
int student_start_year[100];
int ramapo_id[100];
int userChoice;
int index = 0;
int size = 0;
float sum = 0.0;
//seed
srand((unsigned)time(0));
do
{
print_menu();
userChoice = get_selection();
if (userChoice == 1)
{
input_new_student(student_names, student_GPA, student_start_year, index, ramapo_id);
index++;
size++;
}
if (userChoice == 2)
{
print_all(student_names, student_GPA, student_start_year, index, size, ramapo_id);
}
if (userChoice == 3)
{
print_by_year(student_names, student_GPA, student_start_year, index, size);
}
if (userChoice == 4)
{
print_statistics(student_names, student_GPA, student_start_year, index, size, sum);
}
if (userChoice == 5)
{
return 0;
}
} while(userChoice > 0 && userChoice < 5);
return 0;
}
void print_menu()
{
cout << "Please pick from the following menu " << endl;
cout << "1. Add a new student " << endl;
cout << "2. Print all students " << endl;
cout << "3. Print students by year " << endl;
cout << "4. Print student statistics " << endl;
cout << "5. Quit" << endl;
}
int get_selection()
{
int userChoice;
cin >> userChoice;
while (userChoice > 5 || userChoice < 1)
{
cout << "Error: Invalid input, please try again: ";
cin >> userChoice;
}
return userChoice;
}
string get_Name()
{
std::string student_name;
cout << "Please enter the student's name: ";
cin >> student_name;
return student_name;
}
float get_GPA()
{
float student_GPA;
do {
cout << "Please enter the GPA: ";
cin >> student_GPA;
} while(!(student_GPA < 4.0 && student_GPA > 0.0));
return student_GPA;
}
int get_Year()
{
int student_year;
do {
cout << "Please enter the start Year: ";
cin >> student_year;
} while(!(student_year > 1972 && student_year < 2015));
return student_year;
}
void input_new_student(std::string student_names[], float student_GPA[], int student_start_year[], int index, int ramapo_id[])
{
//information generation
int random_integer = rand()%900000 + 100000;
ramapo_id[index] = random_integer;
//information acquisition
student_names[index] = get_Name();
student_GPA[index] = get_GPA();
student_start_year[index] = get_Year();
//Notification
cout << endl;
cout << "The student with R# " << random_integer << " was created." << endl;
cout << endl;
}
void print_all(std::string student_names[], float student_GPA[], int student_start_year[], int index, int size, int ramapo_id[])
{
cout << endl;
for (int i = 0; i < size; i++) {
cout << student_names[i] << " - " << ramapo_id[i] << endl;
}
cout << endl;
}
void print_by_year(std::string student_names[], float student_GPA[], int student_start_year[], int index, int size)
{
int student_year_identifier;
//to trigger the response that there ARE students in that year
bool trigger;
int student_count = 0;
cout << "Which year would you like to display?: ";
cin >> student_year_identifier;
for (int i = 0; i < size; i++)
{
if (student_start_year[i] == student_year_identifier)
{
bool trigger = true;
student_count++;
}
}
if (trigger = true) {
cout << endl;
cout << "There are " << student_count << " student(s) in that year" << endl;
cout << endl;
}
else {
cout << endl;
cout << "There are no students in that year." << endl;
cout << endl;
}
}
void print_statistics(std::string student_names[], float student_GPA[], int student_start_year[], int index, int size, float sum)
{
//Print Total
cout << "Total: " << index << endl;
//Print GPA average
int smart_kids = 0;
float avg = 0.0;
for (int i = 0; i < size; ++i)
{
sum += student_GPA[i];
}
avg = ((float)sum)/size;
cout << "GPA: " << std::setprecision(3) << avg << endl;
//Print # of students above 2.0
for (int i = 0; i < size; i++)
{
if (student_GPA[i] > 2.0)
{
smart_kids++;
}
}
cout << "Above a 2.0: " << smart_kids << endl;
}
I need to write a program that cleans up two arrays with 12 scores and gets rid of the "bonus scores" (where the denominator is 0). I've looked at similar problems, but I'm at a point in which there's three main problems that either no one seems to have or haven't been addressed. the first one is when declaring the new (not bonus) arrays in main it requires that I enter a constant value, however; the size of the arrays must change for the clean_data function to work.
the second one is when calling clean_data in main it marks "deno" and "num" as an error saying that "argument of type int * is incompatible with parameter of type int**", and the last one says that the function clean_data cannot convert argument 1 from int[12] to int*[].
I've been poking at this code for 3 days and looked at my professor's notes and textbook and can't find a way to fix it. please help.
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <cmath>
using namespace std;
//prototypes for functions
void read_data(int nume[], int deno[], int size);
void report_data(int nume[], int deno[], int size);
void report_overall_grade(int nume[], int deno[], int size);
//Data cleanup
void clean_data(int *nume[], int *deno[], int size, int *notBonusNum[], int *notBonusDen[], int &newSize);
int main()
{
//declare constat, arrays, and variables;
const int NUM_GRADES = 12;
int nume[NUM_GRADES];
int deno[NUM_GRADES];
int newSize = 12;
int notBonusNum[newSize];
int notBonusDen[newSize];
//call functions
read_data(nume, deno, 12);
cout << "Original scores: " << endl;
cout << fixed << showpoint << setprecision(1);
report_data(nume, deno, 12);
system("pause");
system("cls");
report_overall_grade(nume, deno, 12);
//Data cleanup
clean_data(nume, deno, 12, notBonusNum, notBonusDen, newSize);
cout << "There are " << newSize << " scores that aren't bonuses:" << endl;
report_data(notBonusNum, notBonusDen, newSize);
system("pause");
return 0;
}
//function definitions
void read_data(int nume[], int deno[], int size)
{
//open file
ifstream inputFile;
inputFile.open("scores.txt");
if (inputFile.fail())
{
cout << "File does not exist." << endl;
system("pause");
exit(1);
}
//read data
int count;
for (count = 0; count < size; count++)
{
inputFile >> nume[count];
inputFile >> deno[count];
}
inputFile.close();
}
void report_data(int nume[], int deno[], int size)
{
int count;
int number = 1;
for (count = 0; count < size; count++)
{
if (deno[count] > 0)
{
int numerator = nume[count];
int denominator = deno[count];
double percent = (double)numerator / denominator * 100;
cout << "Score " << number << " is " << numerator << " / " << denominator << " = " << percent << "%." << endl;
}
else
{
cout << "Score " << number << " is " << nume[count] << " / " << deno[count] << " = Bonus Points!" << endl;
}
number++;
}
}
void report_overall_grade(int nume[], int deno[], int size)
{
int count;
int totalNum = 0;
int totalDeno = 0;
double overallGrade;
for (count = 0; count < size; count++)
{
totalNum += nume[count];
totalDeno += deno[count];
}
cout << "Total points earned: " << totalNum << endl;
cout << "Total points possible: " << totalDeno << endl;
overallGrade = (double)totalNum / totalDeno * 100;
cout << "Overall grade: " << overallGrade << endl;
}
//Data cleanup
void clean_data(int *nume[], int *deno[], int size, int *notBonusNum[], int *notBonusDen[], int &newSize)
{
int count;
for (count = 0; count < size; count++)
{
int count2 = 0;
if (deno[count] != 0)
{
notBonusNum[count2] = nume[count];
notBonusDen[count2] = deno[count];
newSize--;
count2++;
}
}
}
I have to organize my array with a bubble sort to display who works the most hours to who works the least amount of hours. After that, I need to display the employee who makes the most amount of pay in the company. However, I'm not sure how I would go about using a bubble sort with pointer variables and a structure member. At the moment I have a generic code for my bubble sort in the arraySort function but it needs improvement. Thank you!
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
using namespace std;
struct incomeInfo {
string id;
string name;
int hours;
double hRate;
double regPay = 0;
double otPay = 0;
};
const int ARRAY_SIZE = 25;
incomeInfo income[ARRAY_SIZE];
void getIncome(incomeInfo[], int&);
void compute(incomeInfo *, int);
void display(incomeInfo[], int);
void summary(incomeInfo[], int);
void sortArray(incomeInfo[], int);
void mostPay(incomeInfo[], int);
int main()
{
incomeInfo income[ARRAY_SIZE];
int count = 0;
getIncome(income, count);
compute(income, count);
display(income, count);
summary(income, count);
sortArray(income, count);
mostPay(income, count);
return 0;
}
void getIncome(incomeInfo income[], int &count)
{
ifstream inputFile;
char line[50];
inputFile.open("Payroll.txt");
if (inputFile.fail())
{
cout << "\n\n\tError openning file: " << "\n\n\t";
system("pause");
exit(1);
}
else
{
while (!inputFile.eof())
{
inputFile.getline(line, 50, ',');
income[count].id = line;
inputFile.getline(line, 50, ',');
income[count].name = line;
inputFile.getline(line, 50, ',');
income[count].hours = atoi(line);
inputFile.getline(line, 50, ',');
income[count].hRate = atof(line);
count++;
}
}
inputFile.close();
return;
}
void compute(incomeInfo *ptrI, int count)
{
for (int i = 0; i<count; i++)
if (ptrI->hours <= 40)
{
ptrI->regPay = ptrI->hours * ptrI->hRate;
ptrI++;
}
else if (ptrI->hours > 40)
{
ptrI->regPay = 40 * ptrI->hRate;
ptrI->otPay = (ptrI->hours - 40) * (ptrI->hRate + (ptrI->hRate* .5));
ptrI++;
}
return;
}
void display(incomeInfo income[], int count)
{
cout << fixed << showpoint << setprecision(2);
cout << setw(15) << left << "ID" << setw(16) << "Name";
cout << left << setw(8) << "Hours" << setw(14) << "Hourly Rate" << setw(14) << "Regular Pay" << setw(14) << "Overtime Pay" <<endl;
for (int i = 0; i < count; i++)
{
cout << setw(14) << left << income[i].id << setw(15) << income[i].name;
cout << right << setw(6) << income[i].hours << setw(12) << income[i].hRate;
cout << setw(14) << income[i].regPay << setw(14) << income[i].otPay << endl;
}
return;
}
void sortArray(incomeInfo income[], int count)
{
{
bool swap;
int temp;
do
{
swap = false;
for (int count = 0; count < (size - 1); count++)
{
if (array[count] > array[count + 1])
{
temp = array[count];
array[count] = array[count + 1];
array[count + 1] = temp;
swap = true;
}
}
} while (swap);
}
}
void summary(incomeInfo income[], int count)
{
cout << endl << endl << "Total payroll amount for the company = $";
cout << (income[0].regPay + income[0].otPay) + (income[1].regPay + income[1].otPay) + (income[2].regPay + income[2].otPay) + (income[3].regPay + income[3].otPay) + (income[4].regPay + income[4].otPay) << endl;
}
void mostPay(incomeInfo[], int count)
{
cout << endl << endl << "Employee who earns most money: ";
}
The logic for the bubble sort would be the same, except you would be using an array of pointers. Only the if statement needs to change, so that it compares using the values in the structures that the array pointers point to.
Your code won't compile in its current state since you reference 'size' and 'array' variables that do not exist, but here's what a bubble sort looks like:
void sortArray(incomeInfo income[], int count) {
for (int i = 0; i < count; i++)
for (int j = 1; j < count; j++)
if (income[j - 1].hours > income[j].hours)
std::swap(income[j - 1], income[j]);
}
i am relatively new to programming, i just learned c++ and i am getting 2 errors for a HW assignment from school;
Error 2 error C4700: uninitialized local variable 'searchValueptr' used Line 83
and
Error 3 error C4703: potentially uninitialized local pointer variable 'createdArray' used
Line 70
I cannot for the life of me figure out why or how to fix it can some one help me please.
#include <iostream>
#include <iomanip>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
// prototypes
int *createArray(int &size);
void findStats(int *arr, int size, int &min, int &max, double &average);
int *searchElement(int *arr, int size, int *element);
int main ()
{
int choice, size;
bool menuOn = true;
while (menuOn == true)
{
cout << "1 - Create and initialize a dynamic array.\n";
cout << "2 - Display statistics on the array.\n";
cout << "3 - Search for an element.\n";
cout << "4 - Exit.\n";
cout << "Enter your choice and press return: ";
cin >> choice;
cout << endl;
switch (choice)
{
case 1:
int *createdArray;
cout << "Please enter a size for the array: ";
cin >> size;
createdArray = createArray(size);
for (int x=0; x < size; x++)
{
cout << "Value of array at index " << x << ": " << createdArray[x] << endl;
}
cout << endl;
break;
case 2:
int minNum;
int maxNum;
double avgNum;
findStats(createdArray, size, minNum, maxNum, avgNum);
cout << endl << "The maximum number is: " << maxNum;
cout << endl << "The minimum number is: " << minNum;
cout << endl << "The average number is: " << avgNum;
cout << endl << endl;
break;
case 3:
int *searchValueptr;
int searchValue;
cout << "Enter a value to search for: ";
cin >> searchValue;
*searchValueptr = searchValue;
searchElement(createdArray, size, searchValueptr);
break;
case 4:
cout << "Thanks for using this program";
menuOn = false;
break;
default:
cout << "Not a Valid Choice. \n";
cout << "Choose again.\n";
cin >> choice;
break;
}
}
cout << endl;
system("pause");
return 0;
} // end function main ()
int *createArray(int &size)
{
unsigned seed = time(0);
srand(seed);
int *randArray = new int [size];
for (int x=0; x < size; x++)
{
randArray[x] = rand();
}
cout << endl;
return randArray;
}
void findStats(int *arr, int size, int &min, int &max, double &average)
{
min = arr[0];
max = arr[0];
double sum = 0;
for (int count = 0; count < size; count++)
{
if (min >= arr[count])
{
min = arr[count];
}
if (max <= arr[count])
{
max = arr[count];
}
sum += arr[count];
}
average = sum/size;
}
int *searchElement(int *arr, int size, int *element)
{
bool match = false;
for (int count = 0; count < size; count++)
{
if (arr[count] == *element)
{
match = true;
}
}
if (match)
{
cout << "Match Found at: " << element;
return element;
}
else
{
cout << "No Found";
return 0;
}
}
either use
searchValueptr = &searchValue;
or send the pass the address of searchValue
searchElement(createdArray, size, &searchValue);
break;