program crashes at CIN input | C++ - c++

so i made a DOS program however my game always crashes on my second time running to the cin function.
#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace std;
//call functions
int create_enemyHP (int a);
int create_enemyAtk (int a);
int find_Enemy(int a);
int create_enemyDef (int a);
// user information
int userHP = 100;
int userAtk = 10;
int userDef = 5;
string userName;
//enemy Information
int enemyHP;
int enemyAtk;
int enemyDef;
string enemies[] = {"Raider", "Bandit", "Mugger"};
int sizeOfEnemies = sizeof(enemies) / sizeof(int);
string currentEnemy;
int chooseEnemy;
// ACTIONS
int journey;
int test;
int main()
{
// main menu
cout << "welcome brave knight, what is your name? " ;
cin >> userName;
cout << "welcome " << userName << " to Darland" << endl;
//TRAVELING
MENU:
cout << "where would you like to travel? " << endl;
cout << endl << " 1.> Theives Pass " << endl;
cout << " 2.> Humble Town " << endl;
cout << " 3.> Mission HQ " << endl;
cin >> journey;
if (journey == 1)
{
// action variable;
string c_action;
cout << "beware your journey grows dangerous " << endl;
//begins battle
// Creating the enemy, HP ATK DEF AND TYPE. ;
srand(time(0));
enemyHP = create_enemyHP(userHP);
enemyAtk = create_enemyAtk(userAtk);
enemyDef = create_enemyDef(userDef);
chooseEnemy = find_Enemy(sizeOfEnemies);
currentEnemy = enemies[chooseEnemy];
cout << " Here comes a " << currentEnemy << endl;
cout << "stats: " << endl;
cout << "HP :" << enemyHP << endl;
cout << "Attack : " << enemyAtk << endl;
cout << "Defense : " << enemyDef << endl;
ACTIONS:
cout << "Attack <A> | Defend <D> | Items <I>";
cin >> c_action;
//if ATTACK/DEFEND/ITEMS choice
if (c_action == "A" || c_action == "a"){
enemyHP = enemyHP - userAtk;
cout << " you attack the enemy reducing his health to " << enemyHP << endl;
userHP = userHP - enemyAtk;
cout << "however he lashes back causing you to have " << userHP << "health left " << endl;
//end of ATTACK ACTION
}
the last line "cin >> c_action crashes. i use two other pages. they just create the functions. is it a complier issue. also why does my complier always shutdown after it runs he app. is there a way to stop it?

A few hints:
I never use forward declarations of functions ( such as "int create_enemyHP (int a);" ) if I can avoid them. If you do this then there are two places in your code that must be correct for your program to work. It makes life easier if there is always a "single source of truth"
Have you run this code through the debugger? It will help you find problems much more quickly.

If your c_action variable is only intended to be a char, I'd suggest to use a char variable, rather than a string.
You might want to try this way, and if you're still faced with an error, you might give
scanf("%c", &c_action); //assuming you used a char.

I didn't understand if the program crashes before you type the "action" or after. Because if it crashes before, then I think your problems are caused by white spaces characters in the input buffer.

Related

How would I print a multi-line (non-standard) unicode string of text in C++? Updated for Clarity! (hopefully)

Rewriting this question with a bit more knowledge on what I'm requesting; (Thank you James Risner and Turtle for your assistance, but I didn't word this correctly and got different responses than what was needed)
I am currently in the process of writing a program for my class in which I print out non-standard Unicode characters in a string. These characters are direct copies from a website, and not in u\ #### standard copy, but rather the unicode characters pre-selected. The program I am running this on is Clion, building my program using mingw's ninja build settings.
My issue that I'm experiencing is that my output, rather than the unicode characters, is instead a random array of (I think) unrelated characters. Printing this in Clion's Debug menu outputs the proper output, but printing it in the runtime or in its own external file all output the issue.
Below is an exact copy of my code (character for character) DO NOT REUSE PLEASE :(
#include <iostream>
#include <string>
#include <windows.h>
#define _WIN32_WINNT 0x0500
#include <thread>
#include <chrono>
#include <random>
using namespace std;
static int Range(int start, int end){
random_device rd;
mt19937 rng(rd());
uniform_int_distribution<int> dist(start,end);
return dist(rng);
}
int main() {
system("color 0F");
HWND consoleWindow = GetConsoleWindow();
int windowSize = 390;
MoveWindow(consoleWindow, windowSize,windowSize,windowSize,windowSize, TRUE); // This program and the one below it not only locks the window size, but also locks the window at a fixed display pixel length/width
SetWindowLong(consoleWindow, GWL_STYLE, GetWindowLong(consoleWindow, GWL_STYLE) & ~WS_MAXIMIZEBOX & ~WS_SIZEBOX);
ShowScrollBar(GetConsoleWindow(), SB_VERT, 0);
string name = "\033[91m▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀\n\033[92m███╗░░░███╗░█████╗░██████╗░███████╗███╗░░██╗██╗\n\033[93m████╗░████║██╔══██╗██╔══██╗██╔════╝████╗░██║██║\n\033[94m██╔████╔██║██║░░██║██║░░██║█████╗░░██╔██╗██║██║\n\033[95m██║╚██╔╝██║██║░░██║██║░░██║██╔══╝░░██║╚████║██║\n\033[96m██║░╚═╝░██║╚█████╔╝██████╔╝███████╗██║░╚███║██║\n\033[91m╚═╝░░░░░╚═╝░╚════╝░╚═════╝░╚══════╝╚═╝░░╚══╝╚═╝\n\033[92m▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀\n";
float balance = Range(1,50000);
float withD, cSelect;
int x = 0;
while (name[x] != '\0') {
cout << name[x] << flush;
this_thread::sleep_for(chrono::milliseconds(1));
x++;
}
Sleep(2);
std::cout << '\n' << endl;
string bottomBar = "\033[93m░█░█░█░█░█░█░█░█░█░█░█░█░█░█░█░█░█░█░█░█░█░█░█░\n";
string systName = "\033[94mModeni Systems LLC";
cout << " ";
cout << systName << "\n";
std::cout << '\n' << endl;
int y = 0;
while (bottomBar[y] != '\0') {
cout << name[y] << flush;
this_thread::sleep_for(chrono::milliseconds(1));
y++;
}
string Input;
cout << "\n \033[92mPlease Input your Name...\n\n ";
getline(cin, Input);
cout << endl;
cout << " Welcome " << Input << "!" << endl;
cout << " Please select a number from the options below!\n" << endl;
cout << bottomBar << endl;
cout << " 1.) View your Balance\n 2.) Make a withdrawal\n 3.) Deposit\n 4.) Customer Support\n 5.) Log Out Securely\n" << endl;
cout << bottomBar << endl;
cin >> cSelect;
while(cSelect != 5){
if(cSelect==1){
cout << "Your current balance is... " << balance << " dollars!\n \n" << endl;
cout << "Please select a number from the options given below!\n" << endl;
cout << bottomBar << endl;
cout << " 1.)View your Balance\n 2.)Make a withdrawal\n 3.)Deposit\n 4.)Customer Support\n 5.)Log Out Securely" << endl;
cin >> cSelect;
} else if(cSelect==2){
cout << "Please enter the amount you'd like to withdraw!\n" << endl;
cin >> withD;
if(withD>balance){
cout << "Sorry, you do not have that much money! Please try again... " << endl;
} else if(withD<=balance) {
balance = balance - withD;
cout << "Successfully taken out " << withD << " dollars!\n" << "Your new balance is " << balance << " dollars!" << endl;
cout << "Please select a number from the options given below!\n" << endl;
cout << bottomBar << endl;
cout << " 1.)View your Balance\n 2.)Make a withdrawal\n 3.)Deposit\n 4.)Customer Support\n 5.)Log Out Securely" << endl;
cin >> cSelect;
}
} else if(cSelect==3){
cout << "Please enter the amount you'd like to deposit!" << endl;
double depAm;
cin >> depAm;
balance = balance + depAm;
cout << "Your new balance is now " << balance << " dollars!" << endl;
cout << "Please select a number from the options given below!\n" << endl;
cout << bottomBar << endl;
cout << "1.)View your Balance\n2.)Make a withdrawal\n3.)Deposit\n4.)Customer Support\n5.)Log Out Securely" << endl;
cin >> cSelect;
} else if(cSelect==4){
cout << bottomBar << "\n" << endl;
cout << "Hello! This is Modeni's Self-Service Assistant!\n Please describe your problem below! \n" << endl;
string proB;
cin >> proB;
int chatF;
chatF = Range(0,5);
if(chatF==0){
cout << "We're so sorry to hear that! Please wait as we get you in touch with someone who can help.\n" << endl;
} else if(chatF==1){
cout << "Sorry to hear that you're currently having that problem! Please sit tight as we get you in touch with someone who can help.\n" << endl;
} else if(chatF==2){
cout << "That's not good! Please wait just a moment as we get you in touch with someone who can help.\n" << endl;
} else {
cout << "Ouch! Just give us a moment while we put you in touch with someone who can help!\n" << endl;
}
Sleep(10000);
string nameSt;
int nameVar;
nameVar = Range(0,5);
if(nameVar == 1)
nameSt = "Raphael";
else if(nameVar == 2)
nameSt = "Marie";
else if(nameVar == 3)
nameSt = "Joesph";
else
nameSt = "Marian";
cout << " \033[94m░█░█ " << nameSt << " has joined the chat █░█░" << endl;
Sleep(Range(3000,8000));
cout <<"\n >> Just a moment while I look over your concern.\n" << endl;
Sleep(Range(3000,8000));
cout << " >> Alright. I'm sorry you're dealing with this problem right now. Let's put you in touch with one of our call-in agents to assist you further.\n" << endl;
Sleep(Range(3000,8000));
cout << " >> Their number is - 1-(918)-335-1300.\n" << endl;
Sleep(Range(3000,8000));
cout << " >> Is there anything else I can help you with today? \n" << endl;
return 0;
}
}
return 0;
}
I am specifically writing this program for windows, and I have yet to find a solid fix without re-writing the entirety of my code.
The intended output is photograph 1, and the actual output is photograph 2. Any and all help is appreciated!
Photograph 1
Photograph 2
There is no problem with your program. There is a problem with your display.
% cc -o modeni modeni.cpp -lc++
% ./modeni
▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀
███╗░░░███╗░█████╗░██████╗░███████╗███╗░░██╗██╗
████╗░████║██╔══██╗██╔══██╗██╔════╝████╗░██║██║
██╔████╔██║██║░░██║██║░░██║█████╗░░██╔██╗██║██║
██║╚██╔╝██║██║░░██║██║░░██║██╔══╝░░██║╚████║██║
██║░╚═╝░██║╚█████╔╝██████╔╝███████╗██║░╚███║██║
╚═╝░░░░░╚═╝░╚════╝░╚═════╝░╚══════╝╚═╝░░╚══╝╚═╝
▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀
% echo $TERM
xterm-256color
I am using a macOS system and this works with TERM=xterm-256color on both iTerm2 and Terminal.
What is TERM?
This environment variable advises applications what terminal emulation is required to display characters on screen properly. An application will use the termcap/terminfo database to look up the proper escape sequences to display colors, move or manipulative text on screen, and other effects.
I only ever see xterm-256color now. Why?
Modern terminal applications assume the output will be in xterm-256color format. Many no longer have an option to choose another format.
AFAIK there is no standard way in C++ to process unicode in standard io, and different OSs' default consoles will behave differently if you just make the unicode string as std::string to output; E.g. in Windows cmd maybe you need _setmode(_fileno(stdout), _O_U16TEXT); to show UTF-16 strings correctly.
Good news is that in C++23 there will be <print> to (hopefully, not definitely so far) help solve this troublesome problem.

Modularization in C++

I am currently working on a (very very basic) program that is a tutorial for programming( ironic given my knowledge, I know). I was instructed to modularize my code so that each unit is in its own module. I'm guessing that means adding headers? I'm working with Visual Studios, if that helps at all. I've included my code below to help my bad explanation make sense. Thanks for any help you can provide!
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int Total;
int ans;
class Question
{
private:
string Question_Text;
string Answer_one;
string Answer_two;
string Answer_three;
int Correct_Answer;
int Question_Score;
public:
void setValues(string, string, string, string, int, int);
void askQuestion();
};
int main()
{
string username = "";
char choice=' ';
char c;
int x = 4;
int y = 5;
int z = x + y;
//welcome message
cout << "Hello user, please enter your name:";
cin >> username;
cout << "Welcome to the programming tutorial " << username << "." << endl;
//menu selection
while(choice != '5')
{
cout << "What would you like to do? (Unit 1 - Declaring Variables (1), Unit 2 - Input/ Output (2), Unit 3 - Conditionals (3), Quizzes (4) or Exit (5))";
cin >> choice;
if (choice == '1')
{
cout << "We will begin with defining variables. The first step to doing this is choosing which datatype your variable is.\n";
cout << "The following are a few of the common datatypes used in programming.\n";
cout << "Character ==> char\n";
cout << "Integer ==> int, long, double\n";
cout << "Boolean ==> bool\n";
cout << endl;
cout << "When declaring a variable, you must put its datatype before the variable name.\n";
cout << "An example of this would be if we wanted to declare the value of x as 4.\n";
cout << "We would write this as: \n";
cout << "int x = 4\n";
cout << "The program will now use the value 4 for the variable name 'x'\n";
cout << endl;
cout << "Now let's assume we assigned the value of 5 to the variable 'y'\n";
cout << "If we wanted to add x and y and assign the sum to the variable 'z', we would write:\n";
cout << "int z = x + y\n";
cout << "Now when we use the variable 'z' in our program, it will perform the calculation given x=4 and y=5 and declare 9 as the value of the variable 'z'.\n";
cout << "To test our code, we would write: " << endl;
cout << "cout<<'x + y'<< z << endl; \n";
cout << "If written correctly, it will display as: \n";
cout << "x + y = " << z << "." << endl;
}
if (choice == '2')
{
cout << "Now that we understand the basics of declaring variables, let's discuss displaying, or output of, information to a user.\n";
cout << "If you wanted to display a welcome message, for example, you would type:\n";
cout << "cout << 'Welcome';\n";
cout << "The line of code would start with 'cout' followed by two less than signs and then the message you wish to display in quotes.\n";
cout << "Using this, you can ask the user for input.\n";
cout << "Enter c to continue...";
cin >> c;
cout << "Let's say we have a program that flips a coin. You may want to ask the user how many times to flip the coin.\n";
cout << "Assuming we previously declared this amount variable as 'int timesFlipped', we would 'cout' our question and the next line would read:\n";
cout << "cin>> timesFlipped; \n";
cout << "This will store the users input for the variable 'timesFlipped'\n";
cout << "You almost always end a line of code with a semi colon." << endl;
}
if (choice == '3')
{
cout << "This unit will cover conditional expressions." << endl;
}
if (choice == '4')
{
string Question_Text;
string Answer_one;
string Answer_two;
string Answer_three;
int Correct_Answer;
int Question_Score;
Question q1;
Question q2;
Question q3;
cout << username << ", you have chosen to take a quiz." << endl << endl;
int ans, score = 0;
cout << "Unit One Quiz - Variables " << endl << endl;
q1.setValues("How would you declare the value of 'x' as 12? ",
"x=12()",
"x==12()",
"x=12;()",
3,
1);
q2.setValues("What do you need to put before a variable when declaring it?",
"a name()",
"a value()",
"a datatype()",
3,
1);
q3.setValues("Which data type would you use for a number that includes a decimal value?",
"int()",
"double()",
"float()",
2,
1);
q1.askQuestion();
q2.askQuestion();
q3.askQuestion();
cout << "Your score out of a possible 3 is " << Total << endl;
}
if (choice == 'E')
{
cout << "Have a good day!";
break;
}
}
system("pause");
}
void Question::setValues(string q, string a1, string a2, string a3, int ca, int pa)
{
Question_Text = q;
Answer_one = a1;
Answer_two = a2;
Answer_three = a3;
Correct_Answer = ca;
Question_Score = pa;
}
void Question::askQuestion()
{
cout << endl;
cout << Question_Text << endl;
cout << "1. " << Answer_one << endl;
cout << "2. " << Answer_two << endl;
cout << "3. " << Answer_three << endl << endl;
cout << "Please enter your answer: " << endl;
cin >> ans;
if (ans == Correct_Answer)
{
cout << "That is correct!" << endl;
Total = Total + Question_Score;
}
else
{
cout << "Sorry, that is incorrect" << endl;
cout << "The correct answer was " << Correct_Answer << endl;
}
}
I'm guessing that means adding headers?
That's pretty much the idea.
In your case, you may want to:
Create a header name Question.h that includes the declaration of class Question.
Create a source file name Question.cpp and move the class definition there, ie all functions like void Question::askQuestion() etc.
Create a test file name test.cpp to put your main function, and remember to include the Question.h
As you are using Visual Studio, you can create a Project in advance then add all those files before compiling/building.

How to return a variable from one function in C++ to main then use it in another function?

Okay so I have a calorie calculator that is supposed to be separated into the five functions including main seen below. My issue is that I get a compiler error because the variables from the inputNumber function and calculateCalories function cannot be read by any of the other functions once they are obtained. I am not allowed to use Global variables. There must be something I am missing to be able to read the variables within the main function then output them into the other functions to get the proper output. Any help would be appreciated.
Here is the code as it stands:
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
int Lbs, hourr, hourW, hourWe, hourb;
double calBad, calRun, calWal, calWei;
string name;
cout << "Welcome to Megan McCracken's Workout Calculator!" << endl;
cout << endl;
cout << "Please enter your name: ";
getline(cin, name);
inputNumber(Lbs, hourr, hourW, hourWe, hourb);
calculateCalories(Lbs,hourr,hourb,hourW,hourWe,calBad,calRun,calWal,calWei);
displayHeadings(name);
displayLine(hourr,hourb,hourW,hourWe,calBad,calRun,calWal,calWei);
system("pause");
return 0;
}
int inputNumber(int Lbs, int hourr, int hourb, int hourW, int hourWe)
{
cout << "Please enter your weight: ";
cin >> Lbs;
return Lbs;
cout << "Please enter the minutes spent playing badminton: ";
cin >> hourb;
return hourb;
cout << "Please enter the minutes spent running: ";
cin >> hourr;
return hourr;
cout << "Please enter the minutes spent walking: ";
cin >> hourW;
return hourW;
cout << "Please enter the minutes spent lifting weights: ";
cin >> hourWe;
return hourWe;
cout << endl;
}
double calculateCalories(int Lbs, int hourW, int hourb, int hourr, int hourWe, double calBad, double calRun, double calWal, double calWei)
{
const double Badburn = .044, Runburn = .087, Walkb = .036, Weightb = .042;
double calBad, calRun, calWal, calWei;
calBad = (Badburn * Lbs) * hourb;
calRun = (Runburn * Lbs) * hourr;
calWal = (Walkb * Lbs) * hourW;
calWei = (Weightb * Lbs) * hourWe;
return calBad;
return calRun;
return calWal;
return calWei;
}
void displayHeadings(string name)
{
cout << "Here are the results for " << name << ": " << endl;
cout << endl;
cout << "Activity" << right << setw(18) << "Time" << right << setw(10) << "Calories" << endl;
cout << "--------------------------------------" << endl;
}
void displayLine(int hourb,int hourr, int hourW, int hourWe, double calBad, double calRun, double calWal, double calWei)
{
int HB, MB, HR, MR, HW, MW, HWE, MWE, Hour, Min;
double Calorie;
HB = (hourb / 60);
MB = (hourb % 60);
HR = (hourr / 60);
MR = (hourr % 60);
HW = (hourW / 60);
MW = (hourW % 60);
HWE = (hourWe / 60);
MWE = (hourWe % 60);
Calorie = calBad + calRun + calWal + calWei;
Hour = (hourb + hourr + hourW + hourWe) / 60;
Min = (hourb + hourr + hourW + hourWe) % 60;
cout << "Badminton" << right << setw(14) << HB << ":" << setfill('0') << setw(2) << MB << setfill(' ') << right << setw(10) << setprecision(3) << fixed << showpoint << calBad << endl;
cout << resetiosflags(ios::fixed | ios::showpoint);
cout << "Running" << right << setw(16) << HR << ":" << setfill('0') << setw(2) << MR << setfill(' ') << right << setw(10) << setprecision(3) << fixed << showpoint << calRun << endl;
cout << resetiosflags(ios::fixed | ios::showpoint);
cout << "Walking" << right << setw(16) << HW << ":" << setfill('0') << setw(2) << MW << setfill(' ') << right << setw(10) << setprecision(3) << fixed << showpoint << calWal << endl;
cout << resetiosflags(ios::fixed | ios::showpoint);
cout << "Weights" << right << setw(16) << HWE << ":" << setfill('0') << setw(2) << MWE << setfill(' ') << right << setw(10) << setprecision(3) << fixed << showpoint << calWei << endl;
cout << "--------------------------------------" << endl;
cout << resetiosflags(ios::fixed | ios::showpoint);
cout << "Totals" << right << setw(17) << Hour << ":" << setfill('0') << setw(2) << Min << setfill(' ') << right << setw(10) << setprecision(3) << fixed << showpoint << Calorie << endl;
cout << endl;
}
If you want to modify passed-in variables within a function in C++, you should be passing them in by reference (default is by value, meaning you get a copy of the variable which is effectively thrown away when the function exits).
So, by way of example:
void xyzzy (int plugh) { plugh = 42; }
int main() {
int twisty = 7;
xyzzy (twisty);
cout << twisty << '\n';
return 0;
}
will output 7 because twisty was passed by value and changes to it within the function will not be echoed back to the caller.
However, if you pass by reference with:
void xyzzy (int &plugh) { plugh = 42; }
// ^
// This does the trick.
then you'll find it outputs 42 as desired.
For your particular case, you want to look at the variables in the argument list of inputNumber:
int inputNumber(int Lbs, int hourr, int hourb, int hourW, int hourWe)
Any of these that you want echoed back to the caller (and that looks like all of them from a cursory glance) should be pass by reference rather than pass by value.
You should also look into calculateCalories as well, since that is doing the same thing. Keep in mind that only the ones you want to change and echo back to the caller need to be pass-by-reference. So that's only the ones starting with cal.
And, since you're using the pass-by-reference to modify the variables, there's absolutely no reason to return anything from that function so it can be specified as void calculateCalories ... and the return statements removed (in any case, only the first return would have actually done anything, the others would have been unreachable code).
If you haven't yet got to the point where you can use references in your classwork (as seems to be indicated by one of your comments), you can do what C coders have been doing for decades, emulating pass-by-reference with pointers. In terms of the simplified example above, that would mean modifying the function to receive a pointer to the item you want changed, changing what it points to, and calling it with the address of the variable to be changed:
void xyzzy (int *pPlugh) { *pPlugh = 42; }
int main() {
int twisty = 7;
xyzzy (&twisty);
cout << twisty << '\n';
return 0;
}
However, it's a poor substitute for the real thing and, if your educator is trying to teach you that, it's the same as if they're getting you to use printf/scanf rather than cout/cin for user I/O: it's certainly possible in C++ since the language includes legacy C stuff, but it's not really teaching you the C++ way.
People who claim to be C++ developers but really code in C using a C++ compiler, are a rather strange breed that I like to call C+ developers - they've never really embraced the language properly. The sooner people put aside the legacy stuff, the better they'll be as C++ developers.
Pass the variables by references. Then the functions will be able to edit them.
Your other solution (not so much of a good idea but still working) is to create a struct/class and make the functions return it.
P.S. Your code won't work if the functions are in this order unless you add their signatures in the beginning:
int main();
int inputNumber(int,int,int,int,int);
//and so on
In input number, you can not use 'return' to return each value - it will do the first return statement.
In C++ you can use pass by reference so that values assigned to the variables will be passed back up.
In this case, via the input variables would be inputNumber so use '&' to denote the vaiables are references:
void inputNumber(int &Lbs, int &hourr, int &hourb, int &hourW, int &hourWe)
{
.
.
.
}
Similar idea for calculateCalories, get rid of the returns:
void calculateCalories(int Lbs, int hourW, int hourb, int hourr, int hourWe, double &calBad, double &calRun, double &calWal, double &calWei)
{
.
.
}
Note that we are only bothering to pass to reference for the variables that we will be passing back.

I am trying to use a do while loop to repeat a certain portion of my program and it refuses to execute properly

Okay so as the title said its refusing to execute the stuff right under the "do" function even though as far as i can tell all the parameters for a repeat have been fulfilled. So far what i get when i run the program is something along the lines of...
"Would you like to search another name?
Please enter Y for yes and n for no:"
looping over and over when i press y
#include <iostream>
#include <string>
#include <iomanip>
#include <vector>
#include <algorithm>
#include <cstdlib>
using namespace std;
int main()
{
vector <string> vName, vID, vClass;
string sName, sID, sClass, sSearch, cQuestion;
int iSize, iStudent;
// Display initial vector size
iSize = vName.size();
cout << "Student list starts with the size:" << iSize << endl;
// Get size of list from user
cout << "How many students would you like to add?" << endl;
cin >> iStudent;
cin.ignore();
// Get names, ids, and classes
for (int i = 0; i < iStudent; i++)
{
cout << "Student" << i + 1 << ":\n";
cout << "Please enter the student name: ";
getline(cin, sName);
vName.push_back(sName);
cout << "Enter ID number ";
getline(cin, sID);
vID.push_back(sID);
cout << "Enter class name ";
getline(cin, sClass);
vClass.push_back(sClass);
}
// Display header
cout << "The list of students has the size of: " << iStudent << endl;
cout << "The Student List" << endl;
cout << "\n";
cout << "Name:" << setw(30) << "ID:" << setw(38) << "Enrolled Class : " << endl;
cout << "--------------------------------------------------------------------------";
cout << "\n";
// for loop for displying list
for (int x = 0; x < vName.size() && vID.size() && vClass.size(); x++)
{
cout << vName[x] << "\t \t \t" << vID[x] << "\t \t \t" << vClass[x] << endl;
}
// Sorting function
cout << "\n";
cout << "The Student List after Sorting:" << endl;
cout << "\n";
sort(vName.begin(), vName.end());
for (int y = 0; y < vName.size(); y++)
{
cout << vName[y] << endl;
}
cout << "\n";
// Search function
do
{
cout << "Please Enter a name to be searched:" << endl;
getline(cin, sSearch);
if (binary_search(vName.begin(), vName.end(), sSearch))
{
cout << sSearch << " was found." << endl << endl;
}
else
{
cout << sSearch << " was not found." << endl << endl;
}
cout << "Would you like to search another name?" << endl << endl;
cout << "Please enter Y for Yes and N for No:" << endl << endl;
cin >> cQuestion;
} while (cQuestion == "Y" || cQuestion == "y");
cout << "Thank you for using this program!" << endl;
return 0;
}
Edit:
Posted whole program, please excuse any grammatical mistakes, I'm just trying to get the program down before i go in there and make it pretty.
The tail of your loop does this:
cout << "Please enter Y for Yes and N for No:" << endl << endl;
cin >> cQuestion;
which will consume your string if you entered one, but leave the trailing newline in the input stream. Thus when you return to the top of the loop after entering Y or y, and do this:
cout << "Please Enter a name to be searched:" << endl;
getline(cin, sSearch);
the getline will extract an empty line.
How to consume the unread newline from the input stream is up to you. You will likely just end up using .ignore() as you did prior in your program. Or use getline to consume cQuestion. You have options. Pick one that works.
And as a side note, I would strongly advise you check your stream operations for success before assuming they "just worked". That is a hard, but necessary, habit to break. Something like this:
do
{
cout << "Please Enter a name to be searched:" << endl;
if (!getline(cin, sSearch))
break;
if (binary_search(vName.begin(), vName.end(), sSearch))
{
cout << sSearch << " was found." << endl << endl;
}
else
{
cout << sSearch << " was not found." << endl << endl;
}
cout << "Would you like to search another name?" << endl << endl;
cout << "Please enter Y for Yes and N for No:" << endl << endl;
} while (getline(cin,cQuestion) && (cQuestion == "Y" || cQuestion == "y"));
If cQuestion is a char array then you need to use strcmp or stricmp to compare it with another string i.e. "Y" and "y" in this case. If cQuestion is a single char then you need to compare with 'Y' and 'y' (i.e. with a single quote)
Strings in C++ are not first class types therefore they do not have some of the string operation that exist for other basic types like ints and floats. You do have std::string as part of the standard C++ library which almost fulfills the void.
If you just change the type of cQuestion to std::string your code should work but if you want to stick with chars then you will need to change the quote style.

(C++) Goto statement not working. Beginner [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm making a USD to MXN converter and I want to have it work both ways. The if statement works (tryed cout << "test"; and it worked) but it wont work when I replace it with the goto statement.
#include "stdafx.h"
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
int user;
int u, m;
cout << "US/MXN Converter" << endl;
cout << "1 US = 12.99 MXN (6/12/2014)" << endl;
cout << endl;
cout << "What Way to convert" << endl;
cout << "[1] US to MXN" << endl;
cout << "[2] MXN to US" << endl;
cout << "Selection: ";
cin >> user;
if (user == 1)
{
goto USTMXN;
}
else
{
goto MXNTUS;
}
USTMXN:
cout << "Enter the amount of US Dollars to Convert" << endl;
cout << "Amount: ";
cin >> u;
m = u * 12.99;
cout << endl;
cout << "MXN Pesos: " << m << endl;
goto END;
MXNTUS:
int mm, uu;
cout << "Enter the amount of Pesos to Convert" << endl;
cout << "Amount: ";
cin >> mm;
uu = mm / 12.99;
cout << endl;
cout << "US Dollars: " << m << endl;
goto END;
END:
system("PAUSE");
return EXIT_SUCCESS;
}
One of the most fundamental things we have to do as programmers is to learn to break problems into smaller problems. You are actually running into a whole series of problems.
I'm going to show you how to solve your problem. You may want to book mark this answer, because I'm pre-empting some problems you're going to run into a few steps down the line and preparing you - if you pay attention - to solve them on your own ;)
Let's start by stripping down your code.
Live demo here: http://ideone.com/aUCtmM
#include <iostream>
int main()
{
std::cout << "Enter a number: ";
int i;
std::cin >> i;
std::cout << "Enter a second number: ";
int j;
std::cin >> j;
std::cout << "i = '" << i << "', j = '" << j << "'\n";
}
What are we checking here? We're checking that we can ask the user two questions. That works fine.
Next is your use of goto, which I strongly recommend you do not use. It would be better to use a function. I'll demonstrate with your goto case here first:
#include <iostream>
int main()
{
int choice;
std::cout << "Enter choice 1 or 2: ";
std::cin >> choice;
if ( choice == 1 )
goto CHOSE1;
else if ( choice == 2 )
goto CHOSE2;
else {
std::cout << "It was a simple enough question!\n";
goto END;
}
CHOSE1:
std::cout << "Chose 1\n";
goto END;
CHOSE2:
std::cout << "Chose 2\n";
goto END;
END:
std::cout << "Here we are at end\n";
}
live demo: http://ideone.com/1ElcV8
So goto isn't the problem.
That leaves your use of variables. You've really mixed things up nastily by having a second set of variables (mm, uu). Not only do you not need to have these, you're doing something very naughty in that these variables only exist inside one scope and not the other. You can "get away" with this but it will come back to haunt you later on.
The difference in your two main streams of code is the variable names. The second conversion case looks like this:
MXNTUS:
int mm, uu;
cout << "Enter the amount of Pesos to Convert" << endl;
cout << "Amount: ";
cin >> mm;
uu = mm / 12.99;
cout << endl;
cout << "US Dollars: " << m << endl;
goto END;
The problem here is that you have - accidentally - used the variable "m" in your output. It's what we call uninitialized.
cout << "US Dollars: " << m << endl;
That m in the middle should be mm.
Your compiler should actually be warning you about this. If it's not, and you're just setting out learning, you should figure out how to increase the compiler warning level.
It would be better to make a function to do the conversions; you could make one function for each direction, but I've made a function that handles both cases:
#include <iostream>
static const double US_TO_MXN = 12.99;
static const char DATA_DATE[] = "6/12/2014";
void convert(const char* from, const char* to, double exchange)
{
std::cout << "Enter the number of " << from << " to convert to " << to << ".\n"
"Amount: ";
int original;
std::cin >> original;
std::cout << to << ": " << (original * exchange) << '\n';
}
int main() // this is valid since C++2003
{
std::cout << "US/MXN Converter\n"
"1 US = " << US_TO_MXN << " MXN (" << DATA_DATE << ")\n"
"\n";
int choice = 0;
// Here's a better demonstration of goto
GET_CHOICE:
std::cout << "Which conversion do you want to perform?\n"
"[1] US to MXN\n"
"[2] MXN to US\n"
"Selection: ";
std::cin >> choice;
if (choice == 1)
convert("US Dollars", "Pesos", US_TO_MXN);
else if (choice == 2)
convert("Pesos", "US Dollars", 1 / US_TO_MXN);
else {
std::cerr << "Invalid choice. Please try again.\n";
goto GET_CHOICE;
}
// this also serves to demonstrate that goto is bad because
// it's not obvious from the above that you have a loop.
}
ideone live demo: http://ideone.com/qwpRtQ
With this, we could go on to clean things up a whole bunch and extend it:
#include <iostream>
using std::cin;
using std::cout;
static const double USD_TO_MXN = 12.99;
static const double GBP_TO_MXN = 22.03;
static const char DATA_DATE[] = "6/12/2014";
void convert(const char* from, const char* to, double exchange)
{
cout << "Enter the number of " << from << " to convert to " << to << ".\n"
"Amount: ";
int original;
cin >> original;
cout << '\n' << original << ' ' << from << " gives " << int(original * exchange) << ' ' << to << ".\n";
}
int main() // this is valid since C++2003
{
cout << "Foreign Currency Converter\n"
"1 USD = " << USD_TO_MXN << " MXN (" << DATA_DATE << ")\n"
"1 GBP = " << GBP_TO_MXN << " MXN (" << DATA_DATE << ")\n"
"\n";
for ( ; ; ) { // continuous loop
cout << "Which conversion do you want to perform?\n"
"[1] USD to MXN\n"
"[2] MXN to USD\n"
"[3] GBP to MXN\n"
"[4] MXN to GBP\n"
"[0] Quit\n"
"Selection: ";
int choice = -1;
cin >> choice;
cout << '\n';
switch (choice) {
case 0:
return 0; // return from main
case 1:
convert("US Dollars", "Pesos", USD_TO_MXN);
break;
case 2:
convert("Pesos", "US Dollars", 1 / USD_TO_MXN);
break;
case 3:
convert("British Pounds", "Pesos", GBP_TO_MXN);
break;
case 4:
convert("Pesos", "British Pounds", 1 / GBP_TO_MXN);
break;
default:
cout << "Invalid selection. Try again.\n";
}
}
}
http://ideone.com/iCXrpU
There is a lot more room for improvement with this, but I hope it helps you on your way.
---- EDIT ----
A late tip: It appears you're using visual studio, based on the system("PAUSE"). Instead of having to add to your code, just use Debug -> Start Without Debugging or press Ctrl-F5. It'll do the pause for you automatically :)
---- EDIT 2 ----
Some "how did you do that" points.
cout << '\n' << original << ' ' << from << " gives " << int(original * exchange) << ' ' << to << ".\n";
I very carefully didn't do the using namespace std;, when you start using more C++ that directive will become the bane of your existence. It's best not to get used to it, and only let yourself start using it later on when you're a lot more comfortable with C++ programming and more importantly debugging odd compile errors.
But by adding using std::cout and using std::cin I saved myself a lot of typing without creating a minefield of function/variable names that I have to avoid.,
What does the line do then:
cout << '\n' << original << ' ' << from << " gives " << int(original * exchange) << ' ' << to << ".\n";
The '\n' is a single character, a carriage return. It's more efficient to do this than std::endl because std::endl has to go poke the output system and force a write; it's not just the end-of-line character, it actually terminates the line, if you will.
int(original * exchange)
This is a C++ feature that confuses C programmers. I'm actually creating a "temporary" integer with the result of original * exchange as parameters.
int i = 0;
int i(0);
both are equivalent, and some programmers suggest it is better to get into the habit of using the second mechanism so that you understand what happens when you later run into something called the "most vexing parse" :)
convert("Pesos", "British Pounds", 1 / GBP_TO_MXN)
The 1 / x "invert"s the value.
cout << "Foreign Currency Converter\n"
"1 USD = " << USD_TO_MXN << " MXN (" << DATA_DATE << ")\n"
"1 GBP = " << GBP_TO_MXN << " MXN (" << DATA_DATE << ")\n"
"\n";
This is likely to be confusing. I'm mixing metaphors with this and I'm a little ashamed of it, but it reads nicely. Again, employ the concept of breaking problems up into smaller problems.
cout << "Hello " "world" << '\n';
(note: "\n" and '\n' are different: "\n" is actually a string whereas '\n' is literally just the carriage return character)
This would print
Hello world
When C++ sees two string literals separated by whitespace (or comments) like this, it concatenates them, so it actually passes "Hello world" to cout.
So you could rewrite this chunk of code as
cout << "Foreign Currency Converter\n1 USD = ";
cout << USD_TO_MXN;
cout << " MXN (";
cout << DATA_DATE;
cout << ")\n1 GBP = ";
cout << GBP_TO_MXN;
cout << " MXN (";
cout << DATA_DATE;
cout << ")\n\n";
The << is what we call "semantic sugar". When you write
cout << i;
the compiler is translating this into
cout.operator<<(i);
This odd-looking function call returns cout. So when you write
cout << i << j;
it's actually translating it to
(cout.operator<<(i)).operator<<(j);
the expression in parenthesis (cout.operator<<(i)) returns cout, so it becomes
cout.operator<<(i); // get cout back to use on next line
cout.operator<<(j);
Main's fingerprint
int main()
int main(int argc, const char* argv[])
Both are legal. The first is perfectly acceptable C or C++. The second is only useful when you plan to capture "command line arguments".
Lastly, in main
return 0;
Remember that main is specified as returning int. The C and C++ standards make a special case for main that say its the only function where it's not an error not to return anything, in which case the program's "exit code" could be anything.
Usually its best to return something. In C and C++ "0" is considered "false" while anything else (anything that is not-zero) is "true". So C and C++ programs have a convention of returning an error code of 0 (false, no error) to indicate the program was successful or exited without problems, or anything else to indicate (e.g. 1, 2 ... 255) as an error.
Using a "return" from main will end the program.
Try to change youre code for sth like this. Using goto label is not recommended.
Main idea of switch statement :
int option;
cin >> option
switch(option)
{
case 1: // executed if option == 1
{
... code to be executed ...
break;
}
case 99: //executed id option == 99
{
... code to be executed
break;
}
default: // if non of above value was passed to option
{
// ...code...
break;
}
}
Its only example.
int main(int argc, char *argv[])
{
int user;
int u, m;
cout << "US/MXN Converter" << endl;
cout << "1 US = 12.99 MXN (6/12/2014)" << endl;
cout << endl;
cout << "What Way to convert" << endl;
cout << "[1] US to MXN" << endl;
cout << "[2] MXN to US" << endl;
cout << "Selection: ";
cin >> user;
switch(user )
{
case 1 :
{
//USTMXN:
cout << "Enter the amount of US Dollars to Convert" << endl;
cout << "Amount: ";
cin >> u;
m = u * 12.99;
cout << endl;
cout << "MXN Pesos: " << m << endl;
break;
}
}
default :
{
//MXNTUS:
int mm, uu;
cout << "Enter the amount of Pesos to Convert" << endl;
cout << "Amount: ";
cin >> mm;
uu = mm / 12.99;
cout << endl;
cout << "US Dollars: " << m << endl;
break;
}
}
system("PAUSE");
return EXIT_SUCCESS;
}