Unable to detect what line is causing a syntax error - c++

Howdy! I'm working on an old project from one of my programming courses and having some issues tracking down which line in my code is causing a syntax error.
When I attempt to compile the code, Visual Studio tells me that there is a syntax error towards the end of main on the line containing this function call:
sortData(carray, numRec, sortby);
I dont think that's the case, because commenting out that call only moves the error to the next line of code.
I can't tell what is causing the error and am hoping a veteran eye could help.
I've include all of the code as I suspect the error is being caused in one of the function calls.
ohbijuan
P.S. Also - Does anyone know if the compiler compiles top to bottom or whether it actually follows function calls during the compile process?
#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
using namespace std;
//customer struct
struct customer
{
int id;
string fname, lname;
double totalQuantity, totalPurchases, totalProfit;
};
//Error Codes
const int INPUT_FILE_FAIL_NO_CONTINUE = 2;
const int INPUT_FILE_DATA_ERROR = 3;
//Global Constants
const int arraySize = 200;
const int numType = 5; //# of the types of coffee we currently offer
//Coffee prices per pound
const double colombWhole = 3.75;
const double colombRetail = 4.85;
const double konaWhole = 4.25;
const double konaRetail = 5.25;
const double ethiopWhole = 4.30;
const double ethiopRetail = 5.75;
const double jamaWhole = 5.25;
const double jamaRetail = 7.75;
const double brazWhole = 4.65;
const double brazRetail = 5.90;
//Function prototypes
int readData (ifstream &infile, customer carray[], int size);
//PRE: The address of the ifstream object, the addres of the array of customer structs and the size of
// the array is passed in
//POST: All of the customer data is read in AND the totalQuantity, totalPurchases and totalProfit for
// each customer is calculated. The number of records read is returned.
void sortData (customer carray[], int recordcount, int sortfield);
//PRE: The address of the array of customers, the number of customer records in the array and the field
// on which to be sorted is passed into the function.
//POST: The array is sorted on the basis of the specified field in ascending order
int findMax (const customer carray[], int startRange, int recordcount, int sortfield);
//PRE: The address of the array of customers, the field to sort on and a range of values is passed in
//POST: The address of the largest value is returned
int main()
{
//Array of customer structs
customer crecords[arraySize];
//Initialize the members of our struct to zero
for (int i = 0; i < arraySize; i++)
{
crecords[i].totalProfit = 0;
crecords[i].totalPurchases = 0;
crecords[i].totalQuantity = 0;
}
//Declare filestream objects
ifstream ifile;
ofstream ofile1, ofile2, ofile3;
//user responses
char pquit = 'Y';
char specAnother;
int sortby;
string ifilename;
//Ask user for name of input file
cout << "Please enter the name of the input file: " ;
cin >> ifilename;
//Attempt to open the input file
ifile.open(ifilename.c_str());
while (ifile.fail())
{
cout << endl << "The input file could not be found. Would you like to specify "
<< "another file?" << endl << "(Enter Y or N):";
cin >> specAnother; //Ask user if they want to specify another
if (specAnother == 'N' || specAnother == 'n')
{
exit(INPUT_FILE_FAIL_NO_CONTINUE);
}
else
{
cout << endl << "Please enter the name of the new input file: " ;
cin >> ifilename;
}
ifile.clear(); //Clear the flags, else the input file fail flag will perpetually return true
ifile.open(ifilename.c_str());
}
//File opened successfully, let's begin reading in data and also keep track of the # of
//records read
int numRec = readData(ifile, crecords, arraySize);
cout << "Finished reading " << numRec << " records" << endl;
do
{
//Ask user how they would like to sort the data for the report
cout << endl << "What would you like to sort on?" << endl;
cout << "1) Sort by POUNDS bought" << endl
<< "2) Sort by PURCHASE AMOUNT" << endl
<< "3) Sort by PROFIT" << endl;
cin >> sortby;
if (sortby > 3 || sortby < 1)
{
cout << "You entered an invalid sorting method, try again" << endl
<< "Enter an option:";
cin >> sortby;
}
cout << "You entered " << sortby << endl;
}
//Sort Data
sortData(carray, numRec, sortby);
return 0;
}
//Function Definitions
int readData (ifstream &infile, customer carray[], int size)
{
int x = 0, coffeeType, quantity;
double currentSale, internalCost, profitOnSale;
while (infile >> carray[x].id && x < size)
{
infile >> carray[x].fname >> carray[x].lname;
while (infile >> coffeeType && coffeeType != 0)
{
infile >> quantity;
switch(coffeeType)
{
case 1:
carray[x].totalQuantity += quantity;
currentSale = quantity * colombRetail;
carray[x].totalPurchases += currentSale;
internalCost = quantity * colombWhole;
profitOnSale = currentSale - internalCost;
carray[x].totalProfit += profitOnSale;
break;
case 2:
carray[x].totalQuantity += quantity;
currentSale = quantity * konaRetail;
carray[x].totalPurchases += currentSale;
internalCost = quantity * konaWhole;
profitOnSale = currentSale - internalCost;
carray[x].totalProfit += profitOnSale;
break;
case 3:
carray[x].totalQuantity += quantity;
currentSale = quantity * ethiopRetail;
carray[x].totalPurchases += currentSale;
internalCost = quantity * ethiopWhole;
profitOnSale = currentSale - internalCost;
carray[x].totalProfit += profitOnSale;
break;
case 4:
carray[x].totalQuantity += quantity;
currentSale = quantity * jamaRetail;
carray[x].totalPurchases += currentSale;
internalCost = quantity * jamaWhole;
profitOnSale = currentSale - internalCost;
carray[x].totalProfit += profitOnSale;
break;
case 5:
carray[x].totalQuantity += quantity;
currentSale = quantity * brazRetail;
carray[x].totalPurchases += currentSale;
internalCost = quantity * brazWhole;
profitOnSale = currentSale - internalCost;
carray[x].totalProfit += profitOnSale;
break;
default:
cout <<"The input file contains an undeclared coffee type at record " << x
<<"Program terminating!" << endl;
//return exit(INPUT_FILE_DATA_ERROR);
}
}
x++; //At this point, we have encountered our sentinel value of 0 that indicates the end of our
//customer record. Let's move on to the next customer.
}
return x;
}
int findMax (const customer carray[], int startRange, int recordcount, int sortfield)
{
int maxLoc = startRange;
switch(sortfield)
{
case 1:
for (int i = startRange + 1; i <= recordcount; i++)
{
if (carray[maxLoc].totalQuantity < carray[i].totalQuantity)
maxLoc = i;
}
case 2:
for (int i = startRange + 1; i <= recordcount; i++)
{
if (carray[maxLoc].totalPurchases < carray[i].totalPurchases)
maxLoc = i;
}
case 3:
for (int i = startRange + 1; i <= recordcount; i++)
{
if (carray[maxLoc].totalProfit < carray[i].totalProfit)
maxLoc = i;
}
}
return maxLoc;
}
void sortData (customer carray[], int recordcount, int sortfield)
{
for (int i = 0; i < recordcount ; i++)
{
int max = findMax(carray, i, recordcount, sortfield);
swap(carray[i], carray[max]);
}
}

Your problem is that you have this:
do
{
// ...
}
without a trailing while (...); just before the call to sortData.

Where is while clause of your do..while statement?

do { … } requires a condition at the end, such as do { … } while (busy); If you just want to execute a piece of code in a block, just put that block there and remove the do.

Your do {} is missing a while clause after the brackets, that would result in a syntax error.
Another thing I also noticed -- the findMax switch statement is missing a default tag, and it's also missing break statements. Not sure if that's your intention or not, but it's usually not for most switches.

where is your while after do ????
do {
// something
} while(condition);
this is the correct syntax

Related

Access reading violation when trying to use existing struct array

I am writing a program for my class. My program is supposed to create a passenger list. obviously, the list has to be created first, and that option in my program works fine. However when trying to access the second function(pressing B) gives me the following error in the debugger:
Exception thrown at 0x00CD4A76 in ConsoleApplication13.exe: 0xC0000005: Access violation reading location 0x00000000.
I guess that means I am trying to read into an unallocated area in the memory, therefore, the struct array I am using was not created. I am confused since the first option does work, and I am passing the same pointer to both functions therefore the pointer points to the array created in function A.
#include <iostream>
#include <string>
#define _CRT_SECURE_NO_WARNINGS
using namespace std;
struct date
{
int year;
int day;
int month;
};
struct seat
{
int row;
char place;
};
struct pass
{
char * passname;
date bookdate;
seat location;
};
int lastindex;
int initList(pass *p, int x);
int addPass(pass *p, date *D, pass *newpass, int length);
void main()
{
pass *p = {};
int length = 0;
char choice;
do {
cout << "Welcome to FlightDesigner2017.\nEnter one of the following keys to continue:\nA: Create a list of passengers.\nB: Add a passenger to the flight.\n";
cin >> choice;
switch (choice)
{
case 'A':
{
int x;
cout << "How many passengers are on your flight? \n";
cin >> x;
length = initList(p, x);
break;
}
case 'B':
{
pass *newpass=0;
date *D = 0;
switch (addPass(p, D, newpass, length))
{
case '1':
cout << "Passenger successfully added."; break;
case '-3':
cout << "No seats available."; break;
case '-1':
cout << "Seat taken. Try again."; break;
case '-2':
cout << "Passenger is already on the flight."; break;
}
break;
}
}
}
while (choice=!0);
}
int addPass(pass *p, date *D, pass *newpass, int length)
{
#define TAKEN -1
#define SAMENAME -2
#define NOSEATS -3
#define SUCCESS 1
for (int init = 0; init < length; init++)
{
int counter=0;
for (int j = 0; j < length; j++) //empty seats check
{
if (strcmp(p[j].passname , NULL)!=0)
counter++;
}
if (counter == length)
return NOSEATS;
cout << "Enter a seat and row (seat A to F, row 1 to 50): \n"; //taken check
cin >> newpass->location.place >> newpass->location.row;
cout << "\nWhat is the flight date (DD/MM/YYYY)? \n";
cin >> D->day >> D->month >> D->year;
for (int k = 0; k < length; k++)
{
if (D->day == p[k].bookdate.day && D->month == p[k].bookdate.month && D->year == p[k].bookdate.year
&& p[k].location.place == newpass->location.place && p[k].location.row == newpass->location.row)
return TAKEN;
}
cout << "What is the passenger name? \n"; // name check
cin >> newpass->passname;
for (int i = 0; i < length; i++)
{
if (strcmp(newpass->passname,p[i].passname)==0)
return SAMENAME;
}
strcpy(newpass->passname, p[init].passname);
p[init].location.place = newpass->location.place;
p[init].location.row = newpass->location.row;
p[init].bookdate.year = D->year;
p[init].bookdate.month = D->month;
p[init].bookdate.day = D->day;
char ans;
cout << "Enter another passenger? (Y/N)\n";
cin >> ans;
if (ans == 'N')
return SUCCESS;
}
return SUCCESS;
}
int initList(pass *p, int length)
{
p = new pass[length];
for (int i = 0; i < length; i++)
p[i].passname = NULL;
return length;
}
Any explanation on how can I fix this error will help. thanks in advance.

Regarding Structs and Using Them With Array's

I'm trying to write a program that will take every line from a text file and load the value into an array. For some reason however, when I try create a dynamic array and try to put information in any position beyond 0, the information from from position zero gets copied over and I can't seem to understand why. Specifically in this program its in the readInventory function I have written. Basically, why can't I copy one struct to the other?
Sample from file
A009 Strawberries_Case 0 12.50 8
4028 STRAWBERRIES_PINT 0 0.99 104
4383 MINNEOLAS 1 0.79 187.3
4261 Rice_1_LB_Bag 0 0.49 107
Code from program
#include <iostream>
#include <string>
#include <cstring>
#include <iomanip>
#include <fstream>
using namespace std;
struct Product
{
string PLU;
string name;
int salesType;
double unitPrice/*rice per pound*/;
double inventory;
};
struct ItemSold
{
string PLU;
string name;
double cost;
};
Product *inventoryLevels = new Product[100];
ItemSold *itemsSold = new ItemSold[100];
bool readInventory(string filename, int &numberOfItems);
double checkout(int inventoryLength);
double price(string PLU, double units);
int typeCheck(string PLU, int inventoryLength);
string nameCheck(string PLU, int inventoryLength);
int main()
{
int numberOfItems = 0;
string filename = "products.txt";
int total;
if (readInventory(filename, numberOfItems))
{
cout << "Inventory file has errors, please make changes before continuing" << endl << endl;
}
total = checkout(numberOfItems);
cout << total;
system("pause");
}
double checkout(int inventoryLength)
{ // Function that will be used to perform the checkout by the user
string PLU = "1";
double units/*pounds*/;
int salesType;
int counter = 0;
int temp;
double total = 0;
while (PLU != "0")
{
cout << "Enter a PLU: ";
cin >> PLU;
itemsSold[counter].PLU = PLU;
if (PLU == "0")
{
// do nothing
}
else
{
itemsSold[counter].name = nameCheck(PLU, inventoryLength);
if (typeCheck(PLU, inventoryLength) == 0)
{
cout << " Enter the number of units being bought: ";
cin >> units;
while (units > inventoryLevels[counter].inventory)
{
cout << "You have entered in more units than we have on hand \n Please reduce the number of units being bought\n";
cout << " Enter the number of units being bought: ";
cin >> units;
}
itemsSold[counter].cost = price(PLU, units);
inventoryLevels[counter].inventory -= units;
}
else
{
cout << "Enter the number of pounds of the item being bought: ";
cin >> units;
itemsSold[counter].cost = price(PLU, units);
while (units > inventoryLevels[counter].inventory)
{
cout << "You have entered in more pounds than we have on hand \n Please reduce the number of pounds being bought\n";
cout << "Enter the number of pounds of the item being bought: ";
cin >> units;
}
inventoryLevels[counter].inventory -= units;
}
counter++;
}
}
temp = counter;
while (temp >= 0)
{
total += itemsSold[temp].cost;
temp--;
}
return total;
}
string nameCheck(string PLU, int inventoryLength)
{
for (int k = 0; k < inventoryLength; k++)
{
if (inventoryLevels[k].PLU == PLU)
{
return inventoryLevels[k].name;
}
}
return "We are currently out of stock of this item.";
}
int typeCheck(string PLU, int inventoryLength)
{
for (int k = 0; k < inventoryLength ; k++)
{
if (inventoryLevels[k].PLU == PLU)
{
return inventoryLevels[k].salesType;
}
}
}
double price(string PLU, double units)
{ //
double price;
for (int k = 0; k < 100; k++)
{
if (inventoryLevels[k].PLU == PLU)
{
price = units * (inventoryLevels[k].unitPrice);
return price;
}
}
}
bool readInventory(string filename, int &numberOfItems)
{
// File object
fstream inventory;
// Some temp variable used to validate information is still in file while it is being transfered to array
//string temp;
// Open the inventory file
inventory.open(filename);
// Will temporarily hold the properties of an item until loaded onto the array
Product temp;
// Counter will allow for a new item to be stored onto the next available location in the array
int counter = 0;
// Will demonstrate whether or not there is an error
int error = 0;
// Store items and their properties in the global array
while (inventory >> temp.PLU >> temp.name >> temp.salesType >> temp.unitPrice >> temp.inventory)
{
// Checks to see if they
if ((temp.PLU.at(0) > 57) || (temp.PLU.at(1) > 57) || (temp.PLU.at(2) > 57) || (temp.PLU.at(3) > 57))
{
error++;
}
else
{
inventoryLevels[numberOfItems].PLU = temp.PLU;
inventoryLevels[numberOfItems].name = temp.name;
inventoryLevels[numberOfItems].salesType = temp.salesType;
inventoryLevels[numberOfItems].unitPrice = temp.unitPrice;
inventoryLevels[numberOfItems].inventory = temp.inventory;
numberOfItems++;
counter++;
}
}
// If there is no error return true
if (error == 0)
{
return false;
}
// If there is an error return false
else if (error > 0)
{
return true;
}
}
When you assign values here,
while (inventory >> temp.PLU >> temp.name >> temp.salesType >> temp.unitPrice >> temp.inventory)
Am I right to assume that the input file is in the format (since you're assigning each line to the variables?
line 1: Some string you want assigned to PLU
line 2: Some string you want assigned to name
line 3: Some Int you want assigned to salestype
..........
..........
line n:string PLU

Why do all elements for the array object class repeat last entered data C++

I have a class BankAccount with an array made of BankAccount objects. Each object has the name, balance, bank account type, and so forth for each customer. The way this is implemented is through a BankAccount* customers[10] as the classes private field memeber. Customers is then filled with objects made from the chosen constructor. Each piece of data that makes up each object which is an element to customers are all input by the user. In display() data is output, however the problem is that the last inputed object is repeated for each element to customers. Why does this repeat like this? Any help or advice would be great!
BankAccount::BankAccount() : customers()
{
setAcctAmt();
}
void BankAccount::work()
{
for (int x = 0; x < accountAmount; x++)
{
bool t = true;
string theName, sT;
double balance, iRate;
cout << "Enter the name for account " << x + 1 << endl;
cin >> theName;
while (t)
{
if (t == false)
exit;
cout << "Bank Account type: Checking or Saving" << endl;
cin >> sT;
string s;
s = sT.substr(0, 1);
if (s == "c")
{
sT = "Checking Account ";
cout << "Input checking balance: ";
cin >> balance;
iRate = 0.02;
makeAcctNum();
constAcct(theName, balance, iRate, sT); // This is where customers is constructed and data is imput from parameters
t = false;
}
else if (s == "s")
{
sT = "Savings Account ";
cout << "Input saving balance: ";
cin >> balance;
iRate = 0.07;
makeAcctNum();
constAcct(theName, balance, iRate, sT); // The constructed object
t = false;
}
else
cout << "Error, enter checking or saving!" << endl;
}
}
display(); // This is the display function to display all constructed objects of customers
}
// This is the display function
void BankAccount::display()
{
for (int i = 0; i < accountAmount; i++)
{
cout << customers[i]->getAcctNum() << " " << customers[i]->getName() << " " << customers[i]->getType() << " " << customers[i]->getRate()
<< " " << customers[i]->getBalance();
}
}
// This is the constructor that will build each customers element as customer data
BankAccount::BankAccount(string* nam, int* acctNumber, double* balanc, double* rat, string* typ)
{
rate = rat;
account = acctNumber;
name = nam;
type = typ;
bal = balanc;
}
void BankAccount::deleteStuff()
{
delete name, type, bal, rate, account, customers;
}
// This constructs each customers element
void BankAccount::constAcct(string n, double ba, double r, string t)
{
nameS = n;
balD = ba;
rateD = r;
typeS = t;
name = &nameS;
account = &acctNumber;
rate = &rateD;
bal = &balD;
type = &typeS;
for (int i = 0; i < accountAmount; i++)
{
BankAccount* b = new BankAccount(name, account, bal, rate, type);
customers[i] = b;
}
}
Based on this comment and line of code:
// This is where customers is constructed and data is imput from parameters
constAcct(theName, balance, iRate, sT);
It seems your intention is to create a new account using the constAcct method.
Looking at that method:
for (int i = 0; i < accountAmount; i++)
{
BankAccount* b = new BankAccount(name, account, bal, rate, type);
customers[i] = b;
}
You are rewriting all entries in the customers array with a new BankAccount constructed from the same parameters (whatever the last parameters were).
To fix this, you should replace the above loop with something like this:
customers[lastAccountIndex++] = new BankAccount(name, account, bal, rate, type);
Here lastAccountIndex is a variable to keep track of the number of accounts already added.

I'm getting a "string subscript out of range error". I can not figure out why

I searched the site but I am unable to find a solution to my problem. I tried making minor changes but nothing has solved it. I keep getting "string subscript out of range" error. I do not know why. Maybe I'm blind and I'm missing a small error somewhere. Now I'm here requesting aid.
Info on program: This program will input first and last name, validate it and apply case conversion. After the first name and last name have been entered by the user, it will clear the screen and display the names the user has entered. It will then input the product rating, validate it and apply case conversion.Display a heading followed by a bar chart corresponding to the 5 product values.
Edit: I want to say thank you to the people that helped me. I solved the issue finally thankfully to you guys. I have to say that there is a great community here and the response was superb. I'm going to class now but I will post my updated code for people in the future who might have the same problem. Thank you very much again guys.
#include <iostream>
#include <string>
using namespace std;
void Name (string, string&, const int);
void Rating (string&, int[], const int);
void main()
{
const int MAX_FIRST_NAME = 20;
const int MAX_LAST_NAME = 25;
const int MAX_PRODUCTS = 5;
string firstNameQuestion = "First Name";
string lastNameQuestion = "Last Name";
string firstName;
string lastName;
string ratingString;
int ratingInt [MAX_PRODUCTS];
while (true)
{
Name (firstNameQuestion, firstName, MAX_FIRST_NAME);
if (firstName == "Quit")
break;
Name (lastNameQuestion, lastName, MAX_LAST_NAME);
if (lastName == "Quit")
break;
system ("cls");
cout << "First Name: " << firstName;
cout << endl;
cout << "Last Name: " << lastName;
cout << endl;
cout << endl;
Rating (ratingString, ratingInt, MAX_PRODUCTS);
}
}
void Name (string question, string& answer, const int MAX)
{
int count;
do
{
cout << question << " (" << MAX << " chars max. type \"quit\" to stop): ";
getline (cin, answer);
}
while (answer.empty() || answer.length() > MAX);
answer[0] = toupper (answer[0]);
for (count = 1; count < answer.length(); count++)
answer[count] = tolower ( answer[count] );
}
void Rating (string& ratingString, int ratingInt[], const int MAX)
{
int count;
int who;
for (count = 0; count < MAX; count++)
{
do
{
cout << "Rating for product no." << count + 1 << " (A to E): ";
cin >> ratingString[count];
ratingString[count] = toupper (ratingString[count]);
}
while (ratingString.empty() || ratingString.length() > 1 || ratingString[count] > 'E');
}
for (who = 0; who < MAX; who++)
{
if (ratingString[who] == 'A')
ratingInt[who] = 10;
if (ratingString[who] == 'B')
ratingInt[who] = 8;
if (ratingString[who] == 'C')
ratingInt[who] = 6;
if (ratingString[who] == 'D')
ratingInt[who] = 4;
else
ratingInt[who] = 2;
}
cout << endl;
cout << endl;
cout << "Consumer satisfaction bar chart: ";
cout << endl;
for (count = 0; count > MAX; count++)
{
cout << endl;
cout << "Product #" << count + 1 << " ";
for (who = 0; who > ratingInt[count]; who++)
cout << "*";
}
}
Line 45
Rating (ratingString, ratingInt, MAX_PRODUCTS);
the ratingString is empty.
When it runs to Line76
cin >> ratingString[count];
you are referencing an index out of the boundary.
How about this edit:
char cc;
cin >> cc;
ratingString.push_back(cc);
I believe in the loop below, count reached to MAX
for (count = 0; count < MAX; count++)
Then again in loop below, you are using count++ and its going beyond the string ratingString length.
for (who = 0; who < MAX; count++)
To fix the issue, either use correct the index+increment or put a check on string length as well.
for (who = 0; who < MAX && who < ratingString.length(); who++)
It's better to put the string length check in all the loops where character at string index is used.

c++ Division . seemingly simple thing driving me crazy, advice please

Ok i've been programming for about a week now, i started with c++. I'm writing a program that is a kind of an arithmetic trainer, you enter the amount of equations you want, you enter your limit for the random number generator, you specify what kind of equations you want(/*-+), then the program uses a for loop and goes through and generates the equations and their answers in a var and then the users input is checked against this var and if they match another var which is counting the right answers is incremented. After the last equation the program tells the user how many they got right out of how many equations, and by dividing the amount of right answers by the amount of questions then multiplying this value by 100 u should obtain the accuracy percentage for this users arithmetic session. Problem is c++ keeps returning to me a friggin 0 value and i cannot for the life of me work out why in the world c++ is doing this.
entire program:
#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace std;
void menu(void);
class session{
public:
session(){
create_session();
}
void create_session(void){
amount = 0;
range_limit = 0;
rights = 0;
answer = 0;
input = 0;
type = "";
while(amount == 0){
cout << "\nHow many equations do you want?: "; cin >> amount;
if(amount < 1){
cout << "\nAmount is too low!";
amount = 0;
}
}
while(range_limit == 0){
cout << "Enter the number range limit: "; cin >> range_limit;
if(range_limit < 1){
cout << "\nRange limit too low!";
range_limit = 0;
}
}
while(type == ""){
cout << "What equation type do you want?: "; cin >> type;
int strlen = type.size();
if(strlen < 1){
cout << "Invalid type input!";
type = "";
}
}
if(type == "+"){
for(int i=0;i<amount;i++){
int a = random();
int b = random();
answer = a + b;
cout << "\n" << a << " + " << b << " = "; cin >> input;
if(answer == input){
rights++;
}
}
}
cout << "\nYou got " << rights << " answers right out of " << amount << " equations." << endl;
cout << "Accuracy percentage: " << getAccuracy() << "%" << endl;
int post_menu=0;
while(post_menu == 0){
cout << "Enter 1 to create another session or 2 to return to the menu: ";
cin >> post_menu;
if(post_menu == 1){
create_session();
}else if(post_menu == 2){
menu();
}else{
cout << "Invalid input: ";
post_menu = 0;
}
}
}
float getAccuracy(){
float x = (rights/amount)*100;
return x;
}
int random(){
int x = 1+(rand()%range_limit);
return x;
}
void set_amount(int a){
amount = a;
}
void set_range_limit(int r){
range_limit = r;
}
void set_rights(int R){
rights = R;
}
void set_answer(int a){
answer = a;
}
void set_input(int i){
input = i;
}
void set_type(string t){
type = t;
}
private:
int amount;
int accuracy;
int range_limit;
int rights;
int answer;
int input;
string type;
};
int main(){
cout << "=== WELCOME TO ARITH! === \n=========================\n";
menu();
return 0;
}
void menu(void){
//Set the seed for random number gen.
srand(time(0));
//Set var for getting menu input, then get the menu input..
int menu_input;
cout << "\n[1]Create a Session. [2]Exit Arith. \nWhat would you like to do?: ";
cin >> menu_input;
//Now we check what the user wants and act accordingly..
if(menu_input > 2){
cout << "error";
menu_input=0;
}else if(menu_input == 1){
session start;
}else if(menu_input == 2){
cout << "\nExiting Arith!";
}else{
cout << "error";
menu_input=0;
}
}
Troublesome part:
float getAccuracy(){
float x = (rights/amount)*100;
return x;
some how the program is returning 0%.
anyone know why this is so and how to get the result im after.
rights and amount both are int , so when you divide the value is floored, for example if you do 5/2 the answer would be 2 instead of 2.5. To solve this you need to cast one of the variable to float like this: (float(rights)/amount) * 100.
when two int numbers are divided the result will also be int even if temporary variable. so you can make any of the variable float or double or cast it.
You need to convert only one data type because the other will be type promoted implicitly.
float x = ((double)rights/amount)*100;
or you can make your amount variable float by default if it doesnt affect any other part of your code.
Also you have the option to static cast:
float x = (static_cast<double>(rights)/amount)*100;