My function is being seemingly being skipped for no reason - c++

Attempting a basic C++ challenge, (beginner at C++) and I produced this code. I understand that calling a value in an array starts from zero but I wanted the user to type from 1-5 instead of 0-4 because I didn't want to go the easy route and wanted to see if I could do it.
Here is my problem, I made a basic function to subtract 1 from the int choice to allow the user to enter 1-5 but the array see the value as 1-4. However as shown in this image it seems to ignore my function and skip to the next part of the code. I have included my code below.
#include "stdafx.h"
#include <stdlib.h>
#include <iostream>
#include <string>
using namespace std;
string drink[5] = { "Coke", "Water", "Sprite", "Monster", "Diet Coke" };
int choice;
int correct = 0;
void AdjArray()
{
choice--;
};
int main()
{
while (correct != 1)
{
cout << "Enter the number of the beverage you would like." << endl;
cout
<< " Coke = 1\n Water = 2\n Sprite = 3\n Monster = 4\n Diet Coke = 5"
<< endl;
cin >> choice;
AdjArray;
if (choice >= 0 && choice <= 4)
{
cout << "You have chosen " << drink[choice] << "." << endl;
correct = 1;
}
else
{
system("cls");
cout << "Error, you entered: " << choice
<< ". Please enter a number between 1 and 5.\n" << endl;
}
}
return 0;
}

You're not calling your function. Change AdjArray; to AdjArray();

Related

Program loops forever when entering 10 digits on CIN

Can you help me guys? I'm a total beginner. My code worked fine then KEEP LOOPING FOREVER and never goes back to or cmd would crash with "Process terminated with status -1073741676". It should loop once then CIN >> again. It happens when I enter 10 digit numbers in my CIN >>.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
class noteAssign { //This class return "A" if the random number generated is between 1 and 10
public:
int x;
int noteOut(int x){
if(x>1 && x<10){
cout << "ITS A" << endl;
return x;
}else{
cout << "IT'S NOT A" << endl;
return x;
}
}
}gonote;
int main()
{
cout << "Match the note's Hertz!" << endl;
cout << "Your answer may range from 1 to 20" << endl;
cout << "Type 0 to quit" << endl;
int noteIn; //No real purpose YET
do {
srand(time(0)); //ADDING MULTIPLE RAMDOMIZER FOR WIDER RANDOM RANGE
int rand1 = 1+(rand()%20); //randomizer 1
int rand2 = 1*(rand()%20); //randomizer 2
int hzout = (rand1 * rand2 + rand1 / rand2)%20; //rand 3
noteAssign gonote;
cout << gonote.noteOut(hzout) << endl; //calls the function and gives the parameter
cin >> noteIn; //No real purpose YET
} while(noteIn != 0); //program quits when you enter "0"
};

C++ Erase-Remove Idiom not working properly?

This post is a continuation on my post from yesterday: How to output a vector.
So I am in the process of writing a short program that will take a list of strings into a vector, export them to a file, view them before outputting them and lastly remove them if possible. I have managed to get all of the functions working properly except for case 3 (remove a book from the list). The errors I am getting in visual studio as follows:
1.) "No instance of the overloaded function "remove" matches the argument list. [LN 76]
2.) "'Remove': function does not take 2 arguments". [LN 76]
As you can probably tell, I am trying to remove by value instead of index. I am still learning here so be gentle, but why exactly am I getting these errors?
Here is my full code:
#include <iostream>
#include <cctype>
#include <ctype.h>
#include <algorithm>
#include <string>
#include <math.h>
#include <windows.h>
#include <iomanip>
#include <vector>
#include <iostream>
#include <sstream>
#include <fstream>
#include <istream>
// common namespace
using namespace std;
int main()
{
int option;
bool iWannaLeave = false;
vector<string> bookCollection;
string entryVal = " ";
int anotherOption;
do
{
cout << "Welcome to MyBook! - A text recorder framework application." << endl;
cout << "-----------------------------------------------------------" << endl;
cout << "Main Menu:" << endl;
cout << "1 - Add a book to the collection." << endl;
cout << "2 - Display all books currently in the collection." << endl;
cout << "3 - Remove books from the collection." << endl;
cout << "4 - Write stored collection to file." << endl;
cout << "5 - Quit" << endl;
cout << "Make your selection: ";
cin >> option;
cin.ignore();
switch (option)
{
case 1:
{
bool wannaMoreBooks = false;
// the next loop will execute at least one time so you could enter a book
do
{
wannaMoreBooks = false;
cout << "Add a book title to the collection: ";
getline(cin, entryVal);
bookCollection.push_back(entryVal);
cout << "Would you like to enter another book?(1 - yes, 0 - no): ";
cin >> anotherOption;
cin.ignore();
if (anotherOption == 1) wannaMoreBooks = true;
} while (wannaMoreBooks == true);
}
break;
case 2:
{
for (int i = 0; i < bookCollection.size(); i++)
cout << bookCollection[i] << " | ";
cout << endl;
break;
}
case 3:
{
string vecVal;
cout << "Enter the value you would like to remove: " << endl;
cin >> vecVal;
bookCollection.erase(remove(bookCollection.begin(), vecVal), bookCollection.end());
}
// remove a book from the collection
break;
case 4:
{
ofstream fileOut("Collection.txt");
fileOut << "Your MyBook Collection: [Begin] - | ";
auto first = true;
for (string x : bookCollection)
{
if (!first) { fileOut << " | "; }
first = false;
fileOut << x;
}
fileOut << " | - [End]" << endl;
cout << "Collection.txt has been successfully written." << endl;
break;
}
case 5:
{
//Nested IF to kill program properly
int quitVar;
cout << "Are you sure you want to exit the program?: ";
cin >> quitVar;
cin.ignore();
if (quitVar == 1)
{
cout << "The program will now be terminated." << endl;
iWannaLeave = true;
}
else if (quitVar == 0) cout << "Returning to the main menu." << endl;
}
break;
}
} while (iWannaLeave == false);
return 0;
}
I am aware that this is no where near perfect code so in addition to finding out why I am getting these errors I would also like some constructive criticism as to how I can improve.
Additionally: If I wanted to go about using functions in a header file as opposed to a switch, would I just move the case contents to a header file?
Thanks in advance! :)
Virtually all STL-functions take one or more pairs of iterators. Since you just pass begin, there is no viable overload. You need to call
remove(bookCollection.begin(), bookCollection.end(), vecVal)
It is always a good idea to check the reference, which typically also contains a basic usage example.

How to make it possible

My topic may be confusing, this is my code in C++,how can i display the summary of number of student count for each Grade at the end of the program,can any body help in this?
#include <iostream>
#include <fstream>
#include <time.h>
#include <iomanip>
#include <algorithm>
#include <vector>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
int main(int argc, char** argv) {
This is the output i want,can anybody helP?
This is my actual output
[Output of the program][1]
edit: thanks for the responses, since im currently taking a required programming class, and while ive had literally 100% of the material before, I had it all in C++, so im not very good with the syntax yet, and we are told only with functions/loops/methods that have been discussed in lecture , looks like i still need to put more effort into it.
I'm not sure if I understand the problem correctly, but you could increment specified counters each time you determined the grade in your if-else-cascade and then std::cout the results after the while loop.
You could try what Wum suggested, so the code might look like this:
#include <iostream>
#include <fstream>
#include <time.h>
#include <iomanip>
#include <algorithm>
#include <vector>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
int main(int argc, char** argv) {
char date[9];
ifstream in;
ofstream out;
string name;
char grade;
double asg1, asg2, test, quiz, exam, coursework, overallScore, numbergrade;
int numStudentsA = 0;
int numStudentsB = 0;
int numStudentsC = 0;
int numStudentsD = 0;
int numStudentsF = 0;
in.open("Student.txt");
out.open("Result.txt");
in >> name >> asg1 >> asg2 >> test >> quiz >> exam;
//to keep reading the data in input file
while (!in.eof()) {
coursework = asg1 + asg2 + test + quiz;
overallScore = coursework + exam;
if (overallScore >= 70 ) {
grade = 'A';
numStudentsA++;
}
else if (overallScore >= 60) {
grade = 'B';
numStudentsB++;
}
else if (overallScore >= 50) {
grade = 'C';
numStudentsC++;
}
else if (overallScore >= 40) {
grade = 'D';
numStudentsD++;
}
else if (overallScore >= 0) {
grade = 'F';
numStudentsF++;
}// grade
out << left << setw(15) << name ;
out << left << setw(3) <<coursework ; //coursework
out << left << setw(3) << exam ; //exam
out << left << setw(4) << overallScore ; //overall score
out << grade ;
out << endl;
in >> name >> asg1 >> asg2 >> test >> quiz >> exam;
}
cout << "Result Summary Date: " << date << endl;
cout << "Subeject: Programming Methodology" << endl;
cout << "Grade" << setw(10) << "Student" << endl;
cout << "A" << setw(10) << numStudentsA << endl;
cout << "B" << setw(10) << numStudentsB << endl;
cout << "C" << setw(10) << numStudentsC << endl;
cout << "D" << setw(10) << numStudentsD << endl;
cout << "F" << setw(10) << numStudentsF << endl;
cout << "Total Student = 10" << endl;
return 0;
}
I applied a bit of indentation to your code, try to use a single coding style. Also, you should read why the use of eof() is not recommended.
use a array to count the number of students for each grade and print out the array at the end.[ look for inline comments ]
Using a enum to index into the array for easy readability.
Instead of an array you could use maps was one of the suggestions .
eof in the above case is fine as , The first read is outside the while loop and then the check is done at the start. Also the subsequent reads are at the end of the while so the program will loop back right after the read to check the eof conditions and exit (without processing an empty buffer).
The code below checks for while (in>>name>>asg1>>asg2>>test>>quiz>>exam)
#include <iostream>
#include <fstream>
#include <time.h>
#include <iomanip>
#include <algorithm>
#include <vector>
enum { GRADE_A = 0 , GRADE_B = 1, GRADE_C = 2 , GRADE_D = 3 ,GRADE_F = 4}; // use an enum to index into the array for each grade
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
int main(int argc, char** argv) {
char date[9];
_strdate(date);
ifstream in;
ofstream out;
int grades[5]; // to store the grades count
string name;
char grade;
double asg1,asg2,test,quiz,exam,coursework,overallScore,numbergrade;
in.open("Student.txt");
out.open("Result.txt");
grades[GRADE_A] = 0 ; grades[GRADE_B] = 0 ; grades[GRADE_C] = 0 ; grades[GRADE_D] = 0 ; grades[GRADE_F] = 0 ; // initialize array
while (in>>name>>asg1>>asg2>>test>>quiz>>exam) //to keep reading the data in input file
{
coursework = asg1 + asg2 + test + quiz;
overallScore = coursework + exam;
if (overallScore >= 70 )
{grade = 'A' ;grades[GRADE_A]++;} // increment count for each grade
else if (overallScore >= 60)
{grade = 'B' ;grades[GRADE_B]++;}
else if (overallScore >= 50)
{grade = 'C' ;grades[GRADE_C]++;}
else if (overallScore >= 40)
{grade = 'D' ;grades[GRADE_D]++;}
else if (overallScore >= 0)
{grade = 'F' ;grades[GRADE_F]++;}; // grade
out<< left << setw(15) << name ;
out<< left << setw(3) <<coursework ; //coursework
out<< left << setw(3) << exam ; //exam
out<< left << setw(4) << overallScore ; //overall score
out<< grade ;
out<< endl;
}
cout<<"Result Summary Date: " << date << endl;
cout<<"Subeject: Programming Methodology"<<endl;
cout<< "Grade"<< setw(10) << "Student" <<endl;
cout<< "A" <<setw(10)<<grades[GRADE_A]<<endl; // output grade count
cout<< "B" <<setw(10)<<grades[GRADE_B]<<endl;
cout<< "C" <<setw(10)<<grades[GRADE_C]<<endl;
cout<< "D" <<setw(10)<<grades[GRADE_D]<<endl;
cout<< "F" <<setw(10)<<grades[GRADE_F]<<endl;
cout<<setw(0)<<endl;
cout<<"Total Student = 10"<<endl;
//At the end of the program, display the summary of number of student count for each Grade

Sending the return vale to an array in c++

Here is the deal guys:
I'm making a stat generator. The program has a menu(not fully developed in this program, but I have previous code that will work)It asks for a name and then stores it to Character1.
Then it prompts that it is generating your scores.The function GenerateScore() takes 3 random numbers with the range 1-6 each, adds them together and returns the sum.
I want this to loop 6 times and store total into the array Stats[6].
Then I am sending the Character1 and the array to the txt file called charactersave.txt.
It saves whatever name I input each time but I get this when I open the txt file. I get this
anthony-858993460-858993460-858993460-858993460-858993460-858993460-858993460-117763858413957408144036511139574241439271911568132815670376-1177638760
Any help on this would be greatly appreciated,
#include <iostream>
#include <cstring>
#include <array>
#include <string>
#include <fstream>
using namespace std;
int GenerateScore();
int main()
{
int Stats[6];
char Selection;
string Character1;
int i;
cout << "Hello, welcome to my character generator. Please select an option" << endl;// Menu Options
cout << "A: Create Character Name and generate stats" << endl;
cout << "B: Display Name and Stats" << endl;
cout << "C: Quit" << endl;
cin >> Selection; // Menu Selection
cout << endl;
do
{
if ( (Selection == 'a') || (Selection == 'A') )// if user selects a, this happens
{
cout << "Welcome, Before you can start your adventures you must name your character." << endl;
cout << "Please enter your a name." << endl;// prompts user to enter a name for their Caracter
cin >> Character1;
cout << "Thank you now lets generate your stats." << endl;
for (i=0; i<6;i++)// I Want this to run the function GenerateScore() 6 times and input each result into the next element of Stats[6]
{
GenerateScore()>> Stats[i];
}
ofstream savecharinfo("charactersave.txt");// saves the Name and the filled array Stats[6] to the charactersave.txt file
if(savecharinfo.is_open())
{
savecharinfo << Character1;
for(int i = 0; Stats[i]; i++)
{
savecharinfo << Stats[i]; //writing numbers of values2 in the file
}
}
else cout << "File could not be opened." << endl;
break;// this is unfinished after this point
}
}
while ( (Selection != 'c') || (Selection == 'C') ); // ends the program if c or C is entered.
system("PAUSE");
return 0;
}
int GenerateScore()
{
int roll1 = rand()%6+2;
int roll2 = rand()%6+2;
int roll3 = rand()%6+2;
int sum;
sum=roll1+roll2+roll3;
return sum;
}
>> can only be used for std::ostream to achieve streaming behavior.
Change
GenerateScore()>> Stats[i];
to
Stats[i] = GenerateScore();

How can I use 2D array in C++ using Visual Studio?

I'm new to this site and programming in C++ language this semester.
I have been really trying for 2 days and have asked classmates but they do not know either. A classmate said to use the 2D arrays but I don't know what that is and my professor has not gone over 2D arrays.
I am stuck and would really appreciate help.
The input file contains this:
Plain_Egg 1.45
Bacon_and_Egg 2.45
Muffin 0.99
French_Toast 1.99
Fruit_Basket 2.49
Cereal 0.69
Coffee 0.50
Tea 0.75
idk how to display all the "users" orders
Basically a receipt, like he orders this and how many, then ask "u want anything else?", then take the order number and how many again, THEN at the end give back a receipt that looks like this
bacon_and_eggs $2.45
Muffin $0.99
Coffee $0.50
Tax $0.20
Amount Due $4.14
Here is my code:
// Libraries
#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
#include <cmath>
using namespace std;
//structures
struct menuItemType {
string itemName;
double itemCost;
};
// Prototypes
void header();
void readData(menuItemType menu[]);
void Display(menuItemType menu[]);
int main() {
header();
menuItemType menu [8];
readData(menu);
Display(menu);
//system("pause");
return 0;
}
void header() {
char c= 61;
for (int i=0; i < 64; i++) {
cout << c;
}
cout << c << endl;
cout << endl;
cout << "Breakfast Menu" <<endl;
for (int i=0; i < 64; i++) {
cout << c;
}
cout << "" << c << endl;
cout << endl;
}
void readData(menuItemType item[]) {
int i=0;
ifstream in;
in.open("input.txt");
cout << fixed << setprecision(2);
while(!in.eof()) {
in >> item[i].itemName >> item[i].itemCost;
++i;
}
}
void Display(menuItemType item[]) {
int choice = 0, quantity = 0;
double total = 0.0, totalF = 0.0, tax = 0.0;
char exit = 'y';
int j = 1, z = 1, i = 1;
//the Menu
for (int i=0; i<8; i++){
cout << j << ". " << setw(18) << left << item[i].itemName << "$" << setw(10) << item[i].itemCost << endl;
j++;
}
cout << endl;
while(exit == 'y' || exit == 'Y') {
cout << "Please Enter your Selection or 0 to Exit : ";
cin >> choice;
if(cin.fail()) {
cout << "*******Invalid selection*******" << endl;
cin.clear();
cin.ignore(1000,'\n');
} else if (choice==0) {break; }
else {
cout<< "Enter Quantity: ";
cin>> quantity;
if (quantity==0) { break;}
else {
choice--;
total += (quantity * item[choice].itemCost);
tax = (total * .05);
totalF = total + tax;
cout << endl;
}
cout << endl;
cout << "======================================================" << endl;
cout << item[choice].itemName << "\t\t" << item[choice].itemCost << endl;
cout << "======================================================" << endl;
cout << "Do you want to continue (Y/N): ";
cin >> exit;
}
}
}
First off, you don't need a two dimensional array for this! You already have a one dimensional array of a suitable structure, as far as I can tell: Something which stores the name of the object and its price. What is somewhat missing is how many objects are currently in the array and how much space it has. If you want to go with the content of the entire array, make sure that you objects are correctly initialized, e.g., that the names are empty (this happens automatically, actually) and that the prices are zero (this does not).
I'm not sure if it is a copy&paste errors but the headers are incorrectly included. The include directives should look something like this:
#include <iostream>
The actual loop reading the values doesn't really work: You always need to check that the input was successful after you tried to read! Also, using eof() for checking that the loop ends is wrong (I don't know where people pick this up from; any book recommending the use of eof() for checking input loops is only useful for burning). The loop should look something like this:
while (i < ArraySize && in >> item[i].itemName >> item[i].itemCost)
++i;
}
This also fixes the potential boundary overrun in case there is more input than the array can consume. You might want to consider using a std::vector<Item> instead: this class keeps track of how many elements there are and you can append new elements as needed.
Note that you didn't quite say what you are stuck with: You'd need to come up with a clearer description of what your actual problem is. The above is just correcting existing errors and readjusting the direction to look into (i.e., forget about two dimensional arrays for now).