how to cin text - c++

How can I get the user to input text instead of numbers in this program.
haw can i get the cin statement to accept text? Do i have to use char?
int main()
{
using namespace std;
int x = 5;
int y = 8;
int z;
cout << "X=" << x << endl;
cout << "Y=" << y << endl;
cout << "Do you want to add these numbers?" << endl;
int a;
cin >> a;
if (a == 1) {
z = add(x, y);
}
if (a == 0) {
cout << "Okay" << endl;
return 0;
}
cout << x << "+" << y << "=" << z << endl;
return 0;
}
---EDIT---
Why won't this work?
int main()
{
using namespace std;
int x = 5;
int y = 8;
int z;
cout << "X = " << x << " Y = " << y << endl;
string text;
cout << "Do you want to add these numbers together?" << endl;
cin >> text;
switch (text) {
case yes:
z = add(x, y);
break;
case no: cout << "Okay" << endl;
default:cout << "Please enter yes or no in lower case letters" << endl;
break;
}
return 0;
}
Thank you everybody!
If you're interested, you can check out the game I made here.
http://pastebin.com/pmCEJU8E
You are helping a young programmer accomplish his dreams.

You can use std::string for that purpose. Remeber that cin reads your text until white space. If you want to read whole line use getline function from the same library.

Since you are concerned with only 1 character response from the user, as in Do you want to add these numbers? might be concatenated by a (Y/N), you should (in my opinion) use getchar() function if you have intentions to read only 1 character. This is how I would do for an error prone 1 character input handling:
bool terminate = false;
char choice;
while(terminate == false){
cout << "X=" << x << endl;
cout << "Y=" << y << endl;
cout << "Do you want to add these numbers?" << endl;
fflush(stdin);
choice = getchar();
switch(choice){
case 'Y':
case 'y':
//do stuff
terminate = true;
break;
case 'N':
case 'n':
//do stuff
terminate = true;
break;
default:
cout << "Wrong input!" << endl;
break;
}
}
As a reply to your edit
That doesn't work because you cannot pass std::string as an argument to the switch. As I told you, you should read just one character for that purpose. If you insist on using strings, do not use switch, rather go for if else blocks by using the string comparator ==.
cin >> text;
if(text == "yes"){
z = add(x, y);
}
else if(text == "no")
{
cout << "Okay" << endl;
}
else
{
cout << "Please enter yes or no in lower case letters" << endl;
}

You can use std::string.
std::string str;
std::cin>>str; //read a string
// to read a whole line
std::getline(stdin, str);

Related

Why doesn't my vending machine program work correctly?

Program should begin with asking , whether to restock or continue with the current stock. The case 1 ( restock ) works perfectly , however the second case , to continue with the previous stock , returns zeros always if any of the products is zeroed.
In the textfile I have:
Milk: 10
Eggs: 2
Water: 7
Burrito: 10
Bread: 12
exit
How can i fix that ?
#include<iostream>
#include<cstdlib>
#include<fstream>
#include<string>
#include<sstream>
using namespace std;
string productName[5] = { "Milk", "Eggs", "Water", "Burrito", "Bread" };
//int productAmount[5] = { 5,12,10,4,7};
int productAmount[5];
int productPick;
int defaultPick;
int productBuy;
fstream productFile; //we create file
void loadFromFile()
{
productFile.open("productsfile.txt", ios::in);
if (productFile.good() == false)
{
cout << "Unable to load the file. Try again later." << endl;
productFile.close();
exit(0);
}
else
{
ifstream productFile("productsfile.txt");
if (productFile.is_open())
{
cout << "How may I help you?" << endl;
string line;
while (getline(productFile, line))
{
// using printf() in all tests for consistency
cout << line.c_str() << endl;
}
productFile.close();
}
}
}
void saveToFile() //this function saves in the text file the data we've globally declared. It is used only if you want to declare new variables.
{
productFile.open("productsfile.txt", ios::out);
for (int i = 0; i < 5; i++)
{
productFile << i + 1 << ". " << productName[i] << ": " << productAmount[i] << endl;
}
productFile << "6. Exit" << endl;
productFile.close();
}
void askIfDefault()
{
cout << "Do you want to come back to default stock?" << endl;
cout << "1. Yes " << "2. No " << endl;
cin >> defaultPick;
switch (defaultPick)
{
case 1:
for (int i = 0;i < 5;i++)
{
productAmount[i] = 10;
}
saveToFile();
loadFromFile();
break;
case 2:
loadFromFile();
break;
default:
cout << "I don't understand." << endl;
exit(0);
break;
}
}
void productCheck()
{
if (productAmount[productPick - 1] <= 0 || productAmount[productPick - 1] < productBuy)
{
cout << "Unfortunately we have no more " << productName[productPick - 1] << " in stock. Please choose other product from the list below: " << endl;
productAmount[productPick - 1] = 0;
}
else
{
productAmount[productPick - 1] -= productBuy;
}
}
void listOfProducts()
{
cout << "How may I help you?" << endl;
for (int i = 0; i < 5; i++)
{
cout << i + 1 << ". " << productName[i] << ": " << productAmount[i] << endl;
}
cout << "6. Exit" << endl;
}
void order()
{
cin >> productPick;
switch (productPick)
{
case 1:
cout << "How many bottles?" << endl;
cin >> productBuy;
{
productCheck();
saveToFile();
}
break;
case 2:
cout << "How many cartons?" << endl;
cin >> productBuy;
{
productCheck();
saveToFile();
}
break;
case 3:
cout << "How many multi-packs?" << endl;
cin >> productBuy;
{
productCheck();
saveToFile();
}
break;
case 4:
cout << "How many portions?" << endl;
cin >> productBuy;
{
productCheck();
saveToFile();
}
break;
case 5:
cout << "How many batches?" << endl;
cin >> productBuy;
{
productCheck();
saveToFile();
}
break;
case 6:
cout << "See you soon!" << endl;
saveToFile();
system("pause");
break;
case 666:
cout << "You cannot use the secret magic spells here." << endl;
saveToFile();
exit(0);
break;
default:
cout << "Please pick the existing product: " << endl;
saveToFile();
order();
break;
}
}
int main()
{
askIfDefault();
order();
cout << endl;
while (true && productPick != 6)
{
listOfProducts();
order();
saveToFile();
cout << endl;
}
return 0;
}
Maybe unless declaring one global fsteam productFile, try to declare the it inside each of both functions that are using it: 'loadFromFile()' and 'saveToFile()' respectively. At the beginning of them. It should be fine then.
Let me make a few additional suggestions about your code - because it's a bit difficult to follow:
Choose function names which reflect what the function does - and don't do anything in a function which exceeds what its name indicates. For example, if you wrote a function called ask_whether_to_restock() - that function should ask the question, and perhaps even get the answer , but not actually restock even if the answer was "yes" - nor write anything to files. Even reading information from a file is a bit excessive.
If you need to do more in a function than its name suggests - write another function for the extra work, and yet another function which calls each of the first two and combines what they do. For example, determine_whether_to_restock() could call read_current_stock_state() which reads from a file, and also print_stock_state() and, say, get_user_restocking_choice().
Try to avoid global variables. Prefer passing each function those variables which it needs to use (or references/pointers to them if necessary).
Don't Repeat Yourself (DRI): Instead of your repetitive switch(produtPick) statement - try writing something using the following:
cout << "How many " << unit_name_plural[productPick] << "?" << endl;
with an additional array of strings with "bottles", "cans", "portions" etc.

C++ Skipping cin statement. going into infinite loop

For some reason, it goes into the cin statement the first time but then skips it every other time in this code. After running it a few times, I realized it goes into the default case for some reason without even asking for the user input. Why?
Here's the code. It's a menu with a huge switch statement. The functions inside the switch statements aren't relevant here since it's just the overall loop.
int main()
{
Document* myDocs = new Document[10];
int docCount = 0;
bool menu = true;
int userInput = 0;
while ( menu == true )
{
//int userInput = 0;
userInput = 0;
cout << "----------------MENU----------------" << endl << endl;
cout << " --------(1) LOAD DOCUMENT (1)--------- " << endl << endl;
cout << "--------(2) OUTPUT DOCUMENT (2)--------" << endl << endl;
cout << " --------(3) ANALYZE DOCUMENT (3)-------- " << endl << endl;
cout << " ------(4) COMPARE TWO DOCUMENTS (4)------ " << endl << endl;
cout << " ----------(5) ENCRYPT (5)---------- " << endl << endl;
cout << "-----------(6) DECRYPT (6)----------" << endl << endl;
cout << "-------------(7) EXIT (7)--------------" << endl << endl;
cin >> userInput;
string docName;
string outputLoc;
switch (userInput)
{
case 1:
// Function
break;
case 2:
// Function
break;
case 3-8:
// Function
break;
default:
break;
}
Basically, I first enter the first userinput. Let's say I enter 1. Then it goes into case 1. But then after it gets out of case 1, it goes into an infinite loop that keeps displaying the menu. Shouldn't it stop at the cin statement? That's what I dont understand.
EDIT::
Case 1 is the primary one i'm worried about since I'm trying them 1 by and 1 and case 1 doesn't work.
This is the full code for case 1:
case 1: // Load Document
{
string inputLoc;
cout << "Please input the document name:" << endl;
cin >> docName;
myDocs[docCount].setName(docName);
myDocs[docCount].id = docCount;
cout << "Input Location: " << endl;
cin >> inputLoc;
myDocs[docCount].loadDocument(inputLoc);
docCount++;
break;
}
I'm starting to speculate there is something wrong with my loadDocument function.
Here is the code for that:
void Document::loadDocument(string name)
{
ifstream myFile(name);
int numOflines = 0;
string theLine;
char words;
while (myFile.get(words))
{
switch (words)
{
case '.':
numOflines++;
break;
case '?':
numOflines++;
break;
case '!':
numOflines++;
break;
}
}
lineCount = numOflines;
setLineCt(numOflines);
arr = new Line[lineCount];
myFile.close();
char theChar;
ifstream myFile2(name);
int key = 0;
if (myFile2.is_open())
{
for ( id = 0; id < lineCount; id++ )
{
while (myFile2>> noskipws>>theChar && theChar != '.' && theChar != '!' && theChar != '?') // Changed from || to &&
{
//myFile2>> noskipws >> theChar;
theLine[key] = theChar;
key++;
}
myFile2>>theChar;
arr[id].setStr(theLine);
}
}
}
Basically I'm trying to load the document and store the word count and line count from it. Is there something wrong in it?

Function Call in switch statement.

Hey guys I'm trying to work out how to call a function in my code using a switch statement. I have tried to look for many different references but no matter what nothing seems to work if somebody could please put me on the right path that would be a big help. Here's the code:
#include <iostream>
#include <string>
using namespace std;
int playGame(string word);
int main()
{
int choice;
bool menu = true;
do{
cout <<"Please select one of the following options: \n";
cout << "1: Play\n"
"2: Help\n"
"3: Config\n"
"4: Quit\n";
cout << "Enter your selection (1, 2 and 3): ";
cin >> choice;
//*****************************************************************************
// Switch menu to display the menu.
//*****************************************************************************
switch (choice)
{
case 1:
cout << "You have chosen play\n";
int playGame(string word);
break;
case 2:
cout << "You have chosen help\n";
cout << "Here is a description of the game Hangman and how it is played:\nThe word to guess is represented by a row of dashes, giving the number of letters, numbers and category. If the guessing player suggests a letter or number which occurs in the word, the other player writes it in all its correct positions";
break;
case 3:
cout << "You have chosen Quit, Goodbye.";
break;
default:
cout<< "Your selection must be between 1 and 3!\n";
}
}while(choice!=3);
getchar();
getchar();
cout << "You missed " << playGame("programming");
cout << " times to guess the word programming." << endl;
}
int playGame(string word) //returns # of misses
{
//keep track of misses
//guess is incorrect
//repeated guess of same character
//guess is correct
int misses = 0;
int exposed = 0;
string display = word;
for(int i=0; i< display.length(); i++)
display[i] ='*';
while(exposed < word.length()) {
cout << "Miss:" << misses << ":";
cout << "Enter a letter in word ";
cout << display << " : ";
char response;
cin >> response;
bool goodGuess = false;
bool duplicate = false;
for(int i=0 ; i<word.length() ; i++)
if (response == word[i])
if (display[i] == word[i]) {
cout << response << " is already in the word.\n";
duplicate = true;
break;
} else {
display[i] = word[i];
exposed++;
goodGuess = true;
}
if (duplicate)
continue;
if (!goodGuess){
misses ++;
cout << response << " is not in the word.\n";
}
}
cout << "Yes, word was " << word << "." << endl;
return misses;
}
You are not calling playGame function in switch statement,
switch (choice)
{
case 1:
cout << "You have chosen play\n";
//int playGame(string word); // this does not call playGame,
// it re-declare playGame function again
playGame("word"); // this will call playGame with word parameter
//^^^^^^^^^^^^^^^
break;
int playGame(string word);
In your switch statement might be the problem...try:
int misses = playGame(word);
You are trying to return the number of misses from your playGame method so you have to put the return data inside a variable.

Menu driven project

The instructor want us to write a program that can re displays the menu only when the user wants to restart a selection and add an option to continue with another selection.
The problem I have is when the user select a number from 1 to 4 and complete the selection, the program will ask the user if the user want to continue with another selection and when the user says no, the program still ask to select a number without ending program.
here is my code that I've written so far:
#include<iostream>
using namespace std;
int sp;
int speed = 0;
int M, K, c, x;
const int MINspeed = 10;
const int MAXspeed = 40;
int GetSpeed();
int GetMinSpeed();
int GetMaxSpeed();
int CheckContinue();
int selection;
int GetSpeed()
{
char c;
while(true)
{
cout << "\nDo you want the speed in mph or km/h? \n"
<< "\nEnter M or K followed by Enter: " << endl;
cin >> c;
if( (c != 'M')&& (c != 'K'))
{
cout << "Incorrect Selection. Try Again! \n\n";
break;
}
if ( c == 'M')
{
cout << "\nSpeed in mph: " << speed << endl;
return speed;
}
else if(c == 'K')
{
double toKmPerHour = 1.61;
double speedInKmPerHour = speed * toKmPerHour;
cout << "\nSpeed in km/h:" << speedInKmPerHour << endl;
break;
}
CheckContinue();
}
return 0;
}
int GetMinSpeed()
{
cout << "MIN speed = " << MINspeed << endl;
CheckContinue();
return 0;
}
int GetMaxSpeed()
{
cout << "MAX speed = " << MAXspeed << endl;
CheckContinue();
return 0;
}
/*int SetSpeed(int sp)
{
cout << "The Set Speed is " << sp << endl;
return 0;
}
*/
void SetSpeed()
{
cout << "Input your speed: ";
cin >> speed;
CheckContinue();
}
int CheckContinue(void)
{
char x;
while(true)
{
cout << "\nDo you want to continue with another selection? \n"
<< "\nEnter Y or N followed by Enter: " << endl;
cin >> x;
if ( x == 'Y')
{
int selection;
cout << "Selection Menu" << endl;
cout << "--------------" << endl;
cout << "\n1. Set Speed" << endl;
cout << "2. Get Speed" << endl;
cout << "3. Get MAX Speed" << endl;
cout << "4. Get MIN Speed" << endl;
cout << "5. Exit" << endl;
cout << "\nYour selection :" <<endl;
cin >> selection;
switch(selection)
{
case 1:
SetSpeed();
break;
case 2:
GetSpeed();
break;
case 3:
GetMaxSpeed();
break;
case 4:
GetMinSpeed();
break;
case 5:
cout << "Good Bye" << endl;
break;
}
}
else if(x == 'N')
{
break;
}
}
return 0;
}
/*
In this menu function, it will ask the user to input the selection, ranging from 1 to 5.
If the user puts a number that is not between 1 to 5 or letters, then the program will
ask the user to input a valid selection.
*/
void menu()
{
int selection;
cout << "Selection Menu" << endl;
cout << "--------------" << endl;
cout << "\n1. Set Speed" << endl;
cout << "2. Get Speed" << endl;
cout << "3. Get MAX Speed" << endl;
cout << "4. Get MIN Speed" << endl;
cout << "5. Exit" << endl;
int bye = 0;
while(1)
{
cout << "\nYour selection :" <<endl;
cin >> selection;
bye = 0;
if((selection <= 5)&&(selection >= 1))
{
switch(selection)
{
case 1:
SetSpeed();
break;
case 2:
GetSpeed();
break;
case 3:
GetMaxSpeed();
break;
case 4:
GetMinSpeed();
break;
case 5:
cout << "Good Bye" << endl;
bye = -1;
break;
}
}
else
{
cout << "\nPlease input valid selection: " << endl;
cin >> selection;
switch(selection)
{
case 1:
SetSpeed();
break;
case 2:
GetSpeed();
break;
case 3:
GetMaxSpeed();
break;
case 4:
GetMinSpeed();
break;
case 5:
cout << "Good Bye" << endl;
bye = -1;
break;
}
}
if(bye == -1)
{
break;
}
}
}
int main()
{
menu();
return 0;
}//end of main function
This might serve your purpose. Call ask() as per your requirement if it didn't suit you.
#include <iostream>
#include <stdlib.h>
using namespace std;
char * title;
int a , b;
void menu();
void print(const char *c , int res )
{
cout<<"\n\n\n\n\nThe "<<c<<" of "<<a<<" and "<<b<<" is : " <<res<<endl;
}
void add()
{
print("Addition" , (a+b));
}
void sub()
{
print("subtraction" , (a-b));
}
void mul()
{
print("Multiplication" , (a*b));
}
void div()
{
print("Division" , (a/b));
}
void ask()
{
bool call_menu;
char ch;
cout<<"\n\n\n\n\n\n DO you Want to Continue? Y - N: ";
cin>>ch;
if(ch=='Y' || ch=='y')
{
call_menu= true;
}
else
{
if(ch=='N' || ch == 'n')
{
call_menu= false;
}
else
{
cin.clear();
ask();
}
}
if(call_menu)
{
system("clear"); // change this to system("cls") if on windows
menu();
}
else
{
system("clear"); // change this to system("cls") if on windows
cout<<"\n\n\n\n\n\n\n\t\t\tHave a Nice Day ! \n\n\n"<<endl;
}
}
void input(int *first , int *second)
{
system("clear"); // change this to system("cls") if on windows
cout<<"\n\n\n\t\t\t\t Calculator \n\n\n\n"<<endl;
cout<<"Enter the First Number : ";
cin>>(*first);
cout<<"\nEnter the Second Number :";
cin>>(*second);
}
void menu()
{
int ch;
cout<<"\n\n\n\t\t\t\t Calculator \n\n\n\n"<<endl;
cout<<"\n\n\t\t\t1 . Addition"<<endl;
cout<<"\n\n\t\t\t2 . Subtract"<<endl;
cout<<"\n\n\t\t\t3 . Multiply"<<endl;
cout<<"\n\n\t\t\t4 . Division"<<endl;
cout<<"\n\n\t\t\t5 . Exit" <<endl;
cout<<"\n\n\n\n Enter Your Choice : ";
cin>>ch;
if(ch >=1 && ch <5){
input(&a , &b);
}
switch(ch)
{
case 1:
add();
ask();
break;
case 2:
sub();
ask();
break;
case 3:
mul();
ask();
break;
case 4:
div();
ask();
break;
case 5:
exit(0);
break;
default:
system("clear"); // change this to system("cls") if on windows
cin.clear();
cin.ignore();
menu();
break;
}
}
int main(int argc, char **argv)
{
menu();
return 0;
}
Modify it as per your requirement.
There are several problems with the code in your question. The big problem is there is a lot of redundant code that can be easily eliminated by a few minor adjustments. You have both the menu printing and code to act on selections in several places. This is going to make managing the continue process a lot more difficult. By eliminating the redundant code and adjusting the logic in main and and menu you can not only reduce the complexity but make it far easier to manage.
For instance menu can be changed to remove the while loop and return a boolean value to indicate if the user wants to exit. This will allow you to select an option, act on it, then return letting other portions of the program handle asking the user if they want to continue.
The example below is a modification of your original code. It only addresses the logic for asking the user to continue and eliminates the redundant menu code. You should review the entire code and make additional adjustments as necessary.
#include <iostream>
#include <string>
using namespace std;
int sp;
int speed = 0;
int M, K, c, x;
const int MINspeed = 10;
const int MAXspeed = 40;
int GetSpeed()
{
char c;
while(true)
{
cout << "\nDo you want the speed in mph or km/h? \n"
<< "\nEnter M or K followed by Enter: " << flush;
cin >> c;
if( (c != 'M')&& (c != 'K'))
{
cout << "Incorrect Selection. Try Again! \n\n" << flush;
continue;
}
if ( c == 'M')
{
cout << "\nSpeed in mph: " << speed << endl;
return speed;
}
else if(c == 'K')
{
double toKmPerHour = 1.61;
double speedInKmPerHour = speed * toKmPerHour;
cout << "\nSpeed in km/h:" << speedInKmPerHour << endl;
return speed;
}
}
return 0;
}
int GetMinSpeed()
{
cout << "MIN speed = " << MINspeed << endl;
return 0;
}
int GetMaxSpeed()
{
cout << "MAX speed = " << MAXspeed << endl;
return 0;
}
void SetSpeed()
{
cout << "Input your speed: ";
cin >> speed;
}
/*
In this menu function, it will ask the user to input the selection, ranging from 1 to 5.
If the user puts a number that is not between 1 to 5 or letters, then the program will
ask the user to input a valid selection.
returns false if the user has selected the exit option
returns true for all other options
*/
bool menu()
{
cout << "Selection Menu" << endl;
cout << "--------------" << endl;
cout << "\n1. Set Speed" << endl;
cout << "2. Get Speed" << endl;
cout << "3. Get MAX Speed" << endl;
cout << "4. Get MIN Speed" << endl;
cout << "5. Exit" << endl;
int selection;
cout << "\nYour selection :" <<endl;
cin >> selection;
switch(selection)
{
case 1:
SetSpeed();
break;
case 2:
GetSpeed();
break;
case 3:
GetMaxSpeed();
break;
case 4:
GetMinSpeed();
break;
case 5:
cout << "Good Bye" << endl;
return false;
break;
default:
cout << "\nPlease input valid selection: " << endl;
}
return true;
}
int main()
{
for(bool process = true; process;)
{
process = menu();
if(process)
{
for(bool valid = false; !valid;)
{
cout << "\nDo you want to enter another selection? (Yes/No) " << flush;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
string line;
getline(cin, line);
if(line == "No")
{
valid = true;
process = false;
}
else if(line == "Yes")
{
valid = true;
}
else
{
cout << "\nInvalid input\n\n" << flush;
}
}
}
}
return 0;
}//end of main function

Should I use goto statement here?

A fine gentleman told me that goto statements were bad, but I don't see how I can not use it here:
int main()
{
using namespace std;
int x;
int y;
int z;
int a;
int b;
Calc: //How can i get back here, without using goto?
{
cout << "To begin, type a number" << endl;
cin >> x;
cout << "Excellent!" << endl;
cout << "Now you need to type the second number" << endl;
cin >> y;
cout << "Excellent!" << endl;
cout << "Now, what do you want to do with these numbers?" << endl;
cout << "Alt. 1 +" << endl;
cout << "Alt. 2 -" << endl;
cout << "Alt. 3 *" << endl;
cout << "Alt. 4 /" << endl;
cin >> a;
if (a == 1) {
z = add(x, y);
}
if (a == 2) {
z = sub(x, y);
}
if (a == 3) {
z = mul(x, y);
}
if (a == 4) {
z = dis(x, y);
}
}
cout << "The answer to your math question is ";
cout << z << endl;
cout << "Do you want to enter another question?" << endl;
cout << "Type 1 for yes" << endl;
cout << "Type 0 for no" << endl;
cin >> b;
if (b == 1) {
goto Calc;
}
cout << "Happy trails!" << endl;
return 0;
}
It is a calculator, as you can see. Also, if you want, can you suggest a better way (If it exists) to let the user choose the operation (+ - * /). Header files are under control.
I apologize for a lot of cout statements.
Here is a cleaned-up and properly formatted version using a do/while loop for structure:
using namespace std;
int main()
{
int x, y, z, a, b;
do {
cout << "To begin, type a number" << endl;
cin >> x;
cout << "Excellent!" << endl;
cout << "Now you need to type the second number" << endl;
cin >> y;
cout << "Excellent!" << endl;
cout << "Now, what do you want to do with these numbers?" << endl;
cout << "Alt. 1 +" << endl;
cout << "Alt. 2 -" << endl;
cout << "Alt. 3 *" << endl;
cout << "Alt. 4 /" << endl;
cin >> a;
if (a == 1) {
z = add(x, y);
}
else if (a == 2) {
z = sub(x, y);
}
else if (a == 3) {
z = mul(x, y);
}
else if (a == 4) {
z = dis(x, y);
}
cout << "The answer to your math question is ";
cout << z << endl;
cout << "Do you want to enter another question?" << endl;
cout << "Type 1 for yes" << endl;
cout << "Type 0 for no" << endl;
cin >> b;
} while (b != 0);
cout << "Happy trails!" << endl;
return 0;
}
Erm , use a proper looping construct, while, for etc.
the "more generally accepted" approach in this case would be a do {...} while(b==1); but the compiled results would likely be identical.
goto makes it difficult to track where execution is coming from, and where it's going.
goto encourages spagetti-code, unless you restrict heavily where it is used (e.g. you could argue that you only use it for cleanup blocks, but such an argument makes no sense in the presence of RAII).
you are using a goto to simulate a loop. Why are you not writing a loop instead?
it's obscure and thus, makes your code less available to other people.
goto makes it more difficult to track objects lifetimes.
Short answer to actual question: No, you should not use goto in this code. There is no need for it.
The use of goto should be "when it makes the code clearer or safer". The typical example of "makes the code clearer" is when there several layers of nested loops, and some particular situation requires leaving all the nesting levels, and adding a "do we want to exit the loop" makes the code more complicated. An example of "making it safer" is if a function holds a lock, opens a file or something similar, and needs to return early - but you also need to close the file or release the lock, using "goto exit_now;" is safer than trying to remember what locks, files, etc are held and then doing return;.
This:
if (a == 1) {
z = add(x, y);
}
if (a == 2) {
z = sub(x, y);
}
if (a == 3) {
z = mul(x, y);
}
if (a == 4) {
z = dis(x, y);
}
is a classic case of you should use 'switch':
switch(a)
{
case 1:
z = add(x, y);
break;
case 2:
z = sub(x, y);
break;
....
}
Makes the code clearer - there is also no confusion about whether a changes value and maybe another if statement becomes viable.
You can easily avoid 'goto' in your code. Just divide it into functions:
using namespace std;
void question () {
cout << "To begin, type a number" << endl;
cin >> x;
// put rest of the code here
}
int main () {
int ask = 1;
while ( ask == 1 ) {
question();
cout << "Do you want to enter another question?" << endl;
cout << "Type 1 for yes" << endl;
cout << "Type 0 for no" << endl;
cin >> ask;
}
return 0;
}
Edit: as noted in the comments, using do-while would be actually an better option.
goto isn't automatically bad. Unreadable code is bad. Whenever you find yourself in need of some obscure programming construct like 'goto', that usually means that your code is either poorly written, or that your program design is flawed.
The solution is almost always more functions. For example:
bool run_program();
int prompt_user_begin();
int prompt_user_again();
int prompt_operation_type();
bool prompt_continue();
int main()
{
while(run_program())
{}
cout << "Happy trails!" << endl;
return 0;
}
bool run_program()
{
int first;
int second;
int operation_type;
int result;
first = prompt_user_begin();
cout << "Excellent!" << endl;
second = prompt_user_again();
cout << "Excellent!" << endl;
operation_type = prompt_operation_type();
switch(operation_type)
{
case 1: result = add(first, second); break;
case 2: result = sub(first, second); break;
case 3: result = mul(first, second); break;
case 4: result = div(first, second); break;
}
cout << "The answer to your math question is ";
cout << result << endl;
return prompt_continue();
}
int prompt_user_begin ()
{
int x;
cout << "To begin, type a number" << endl;
cin >> x;
return x;
}
int prompt_user_again ()
{
int x;
cout << "Now you need to type the second number" << endl;
cin >> x;
return x;
}
int prompt_operation_type ()
{
int x;
cout << "Now, what do you want to do with these numbers?" << endl;
cout << "Alt. 1 +" << endl;
cout << "Alt. 2 -" << endl;
cout << "Alt. 3 *" << endl;
cout << "Alt. 4 /" << endl;
cin >> x;
return x;
}
bool prompt_continue ()
{
int x;
cout << "Do you want to enter another question?" << endl;
cout << "Type 1 for yes" << endl;
cout << "Type 0 for no" << endl;
cin >> x;
return x==1;
}