I'm trying to get an idea of how this control syntax works.
Note: this is part of my int.main function:
while(cin >> Options){
if(Options == 1){ //If I enter '1' here it will output: "aHi.Else."
cout << "a";
}else{
cout << "hi";
}
if(Options == 2){ //If I enter '2' here it will output: "hiaElse."
cout << "a";
}else{
cout <<"Hi.";
}
if(Options == 3){ //If I enter '3' here it will output: "hiHi.a"
cout << "a";
}else{
cout << "Else." << endl;
}
}
Why is it dripping over to else's and stuff? What's wrong with the syntax? I'm confused?
How am I supposed to use multiple if statements without else's included? Can you give an example?
The ifs are not dependent on each other, so if Options is anything but 1, it will execute the else branch of the first if statement, even if Options is 2 or 3. The same applies to the other ifs. Since Options can only be 1 or 2 or 3 (or something else), you will always get the else output for the other ifs.
You can chain else and if if you want to link multiple conditions to each other. In the example below, the last else only executes if Options is neither 1, nor 2, nor 3.
while(cin >> Options){
if(Options == 1){
cout << "a";
}
else if(Options == 2){
cout << "b";
}
else if(Options == 3){
cout << "c";
}
else{
cout << "Hello";
}
}
or using a switch statement:
while(cin >> Options){
switch(Options){
case 1:
cout << "a";
break;
case 2:
cout << "b";
break;
case 3:
cout << "c";
break;
default:
cout << "Hello";
}
}
Related
I'm making a calculator program but I already encounter a problem. Well, my code is in a loop that will call a function to display the choices and then ask the user to pick, a/s/m/d are the choices. If the input is on the choices, it will proceed to the next step. Otherwise, it will loop and then call the function again.
#include <iostream>
using namespace std;
void home()
{
cout << "\nChoose your operation:" << endl;
cout << "\tType [A] for Addition" << endl;
cout << "\tType [S] for Subtraction"<< endl;
cout << "\tType [M] for Multiplication" << endl;
cout << "\tType [D] for Division" << endl;
}
int main()
{
char operation;
bool no_operator = true;
int design = 73;
for (int i = 0; i < design; i++){
if (i == 25){
cout << " WELCOME TO CALCULATOR ";
i += 22;
}
else i == 72 ? cout << "*\n" : cout << "*";
}
while (no_operator){
home();
cout << "\nOperation: ";
cin >> operation;
if (operation == 'A' || operation == 'a')
{
cout << "\nIt will going to add numbers";
no_operator = false;
}
else if (operation == 'S' || operation == 's')
{
no_operator = false;
cout << "\nIt will going to subtract numbers";
}
else if (operation == 'M' || operation == 'm')
{
no_operator = false;
cout << "\nIt will going to multiply numbers";
}
else if (operation == 'D' || operation == 'd')
{
no_operator = false;
cout << "\nIt will going to divide numbers";
}
else
{
cout << "\tInvalid Input: You must enter A/S/M/D only\n";
//home();
}
}
return 0;
}
My problem is it will run the '''home()''' in else statement even if the input is correct on the second loop.
I want to stop the '''home()''' to be called when the input is correct
Your code works perfectly fine. Make sure you're inputting the correct letters.
Also for this code, a "do while()" loop would be better.
You program is working perfectly fine as the input is correct it does not show the home rather print the message it will going to divide etc.
Basically, this program allows a user to enter a sentence and depending on the users selection, it will show the middle character of the sentence, display it uppercase or lowercase, or backwards. Simple program, but I am new to programming so that may be the problem. I would like to figure out how to use loops instead of a ton of if statements. When I try to make some loops it breaks certain parts of the code but I am sure that is because I don't properly understand them. If you have any criticism or any advice on the code, I'd be happy to hear it. Thanks in advance!
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
int sel;
string sent;
bool validinput;
int i;
int x;
int j;
int a;
cout << "Welcome to my program. Enter a sentence and select one of the options below.\n";
cout << "Enter -999 to exit the program." << endl;
cout << "============================================================================" << endl;
cout << endl;
cout << "1. Display the middle character if there is one." << endl;
cout << "2. Convert to uppercase." << endl;
cout << "3. Convert to lowercase." << endl;
cout << "4. Display backwards." << endl;
cout << "Enter a sentence: ";
getline (cin, sent);
cout << "Selection: ";
cin >> sel;
if (sel < 1 && sel > 4)
{
cout << "Invalid input. Try again. Selection: ";
cin >> sel;
validinput = false;
}
else (sel >= 1 && sel <= 4);
{
validinput = true;
}
if (validinput == true)
{
if (sel == 1)
{
j = sent.length() / 2;
cout << "The middle character is: " << sent.at(j) << endl;
}
if (sel == 2)
{
for (int i = 0; i < sent.length(); i++)
{
if (sent.at(i) >= 'a' && sent.at(i) <= 'z')
{
sent.at(i) = sent.at(i) - 'a' + 'A';
}
}
cout << "Uppercase: " << sent << endl;
}
if (sel == 3)
{
for (int x = 0; x < sent.length(); x++)
{
if (sent.at(x) >= 'A' && sent.at(x) <= 'Z')
{
sent.at(x) = sent.at(x) - 'A' + 'a';
}
}
cout << "Lowercase: " << sent << endl;
}
if (sel == 4)
{
for (a = sent.length() - 1; a >= 0; a--)
{
cout << sent.at(a);
}
}
}
system("pause");
return 0;
}
Personally I would use the switch selection statement. I roughly did this just to explain a bit on how it can make your code more friendly and understandable.
int sel;
bool validInput = false;
switch(sel)
{
case 1:
//display middle char if there's one
case 2:
//convert to uppercase
case 3:
//convert to lowercase
case 4:
//display backwards
validInput = true;
break;
default: //if number does not meat 1, 2, 3 or 4
validInput = false;
break;
}
As you may notice, for case 1, case 2, case 3 and case 4, there's a break just to say that if the number is between 1 to 4; validInput is true.
Reference: Switch Selection Statement
i suggest using a switch. It will organize your code better. From looking at your code you seem to have used for and if wisely. But I suggest the if statements checking for the input be replaced with switch.
I am currently making a program that has menu and sub menus and i'd like to have an opportunity to close entire thing from within any sub menu (which is inside function). I know i could do it different way (both way i have it now and way i know it could be done are below) but for future use (i could prove useful) i would like to know:
Is there a way to properly close the program from within a function ?
I've read a few answers here and here and from what i've gotten out of it is:
I should not simply terminate the code
I should not use any system specific code as to avoid compatibilty issues
A bit of clarifiacation - that is program for my personal educational purposes so it is kind of unnecessary to worry about it but i'd rather learn propper ways of dealing with those situations at the beginning than have to learn them anew once i discover how to do them later and have to go back and fix it.
As for code samples (using visual studio 2017):
//skipping unrelevant to question bits of code
void sub_menu()
{
char a=0;
system("cls"); //yet to get changed when i'll find other way of clearing screen
std::cout << "Pick function:\n"
<< "---------------------------------------------------------\n"
<< "1.Foobar_1\n"
<<"---------------------------------------------------------\n"
<< "ESC to go back to menu menu\n"
<< "x to close";
while (a != 27)
{
a = _getch();
switch (a)
{
case 49:foobar_1(); break;
case 120:
case 88: system("exit"); break; //i'd like to replace that part
default: break;
};
};
return;
}
void main()
{
char a=0;
system("cls"); //yet to get changed when i'll find other way of clearing screen
std::cout << "Pick what you want to do:\n"
<< "---------------------------------------------------------\n"
<< "1.Sub_menu\n"
<< "2.foo\n"
<< "3.bar\n"
<<"---------------------------------------------------------\n"
<< "ESC to close\n"
while (a != 27)
{
a = _getch();
switch (a)
{
case 49:sub_menu(); break;
case 50:foo(); break;
case 51:bar(); break;
case 120:
case 88: system("exit"); break; //i'd like to replace that part
default: break;
};
};
return;
}
The way i could implement it (i think it is merely byapssing the issue):
//skipping unrelevant to question bits of code
void main()
{
char a=0;
system("cls"); //yet to get changed when i'll find other way of clearing screen
std::cout << "Pick what you want to do:\n"
<< "---------------------------------------------------------\n"
<< "1.Sub_menu\n"
<< "2.foo\n"
<< "3.bar\n"
<<"---------------------------------------------------------\n"
<< "ESC to close\n"
while (a != 27)
{
a = _getch();
switch (a)
{
case 49:
{
{
char b=0;
system("cls");
std::cout << "Pick function:\n"
<< "---------------------------------------------------------\n"
<< "1.Foobar_1\n"
<<"---------------------------------------------------------\n"
<< "ESC to go back to menu menu\n"
<< "x to close";
while (b != 27)
{
b = _getch();
switch (b)
{
case 49:foobar_1(); break;
case 120:
case 88: a=27; break;
default: break;
};
};
return;
}
}
; break;
case 50:foo(); break;
case 51:bar(); break;
case 120:
case 88: system("exit"); break; //i'd like to replace that part
default: break;
};
};
return;
}
This Code will work as you mentioned.
int main()
{
int a;
while (true)
{
system("cls"); //yet to get changed when i'll find other way of clearing screen
cout << "Pick what you want to do:\n"
<< "---------------------------------------------------------\n"
<< "1.Sub_menu\n"
<< "2.foo\n"
<< "3.bar\n"
<< "---------------------------------------------------------\n"
<< "0. to close\n";
cin >> a ;
if (a == 0)
{
return 0 ;
}
else if (a == 1)
{
char b;
while (true)
{
system("cls");
cout << "Pick function:\n"
<< "---------------------------------------------------------\n"
<< "1.Foobar_1\n"
<< "---------------------------------------------------------\n"
<< "b to go back to menu menu\n"
<< "x to close\n";
cin >> b;
if (b == '1')
{
foobar_1();
}
else if (b == 'B' || b == 'b')
{
break;
}
else if (b == 'x' || b == 'X')
{
return 0;
}
else
{
cout << "invalid input";
}
}
}
else if (a == 2)
{
foo();
}
else if (a == 3)
{
bar();
}
else
{
cout << "invalid input";
}
}
return 0;
}
So I'm working on a little bit of a project involving AI, and I have run into a problem. The program should use a for loop to search the index of common known phrases, and if they don't match the sentence, then in the else statement it figures out which sentence model to apply, then generates output using that sentence model. Here are the built in phrases, they are stored in arrays:
string greetings[6] = {"hey", "hello", "hi", "hey max", "hello max", "hi max"};
string howsItGoing[6] = {"hows it going?","how's it going max?","hows it going max?", "whats up?", "whats up max?"};
string whatsYourName[6] = {"whats your name?", "what's your name?" , "whats your name max?", "what's your name max?"};
string dogsOrCats[6] = {"do you like dogs or cats?", "do you like cats or dogs?", "which do you like more cats or dogs?", "which do you like more dogs or cats?"};
string areYouAlive[6] = {"hey max are you alive?", "hey are you alive?", "max are you alive?", "are you alive?"};
string favoriteColor[6] = {"whats your favorite color?", "what's your favorite color?", "what is your favorite color?", "max whats your favorite color?", "max what's your favorite color?", "max what is your favorite color?"};
string whatGender[6] = {"are you a boy or a girl?", "are you boy or girl?", "are you a guy?", "max are you a boy or girl?", "max are you a guy?", "are you a boy or girl?"};
(This is a temporary method, I'm devising a little thing called a Sentence Decoder that will eventually replace all built in phrases.)
So my problem is this: In the for loop, the first if statement can search the entire array and respond with a suitable output, whether the input was greetings[0] or greetings [4]. However, all the else-if statements appear to be just looking for index 0. I believe this has to do with the for loop only searching across the first one 6 times, but I'm mostly likely wrong. I tried increasing the for loop end-number from 6 to 40 to see if that would help, but alas it didn't make a difference. Here is the rest of the code (It's so ugly! I need to make a function for it or something.... but then again, the whole thing itself is a function...
for (int i = 0; i < 6; i++) {
//Checking if it fits in any of the known greetings
if (input == database.greetings[i]) {
if (timesBeenGreeted == 0) {
cout << "Oh, hey." << endl;
timesBeenGreeted++;
break;
}
else if (timesBeenGreeted == 1) {
cout << "hello?" << endl;
timesBeenGreeted++;
break;
}
else if (timesBeenGreeted == 2) {
cout << "You've said hi to me twice now." << endl;
timesBeenGreeted++;
break;
}
else if (timesBeenGreeted >= 3) {
cout << "Stop. It." << endl;
timesBeenGreeted++;
break;
}
i = 0;
continue;
}
else if (input == database.howsItGoing[i]){
if (askedHowsItGoing == 0) {
cout << "Yeah, not bad." << endl;
askedHowsItGoing++;
break;
}
else if (askedHowsItGoing == 1) {
cout << "Um, yeah, I'm good? You've already asked that." << endl;
askedHowsItGoing++;
break;
}
else if (askedHowsItGoing == 2) {
cout << "Alright, look. I already told you I'm fine, two times now." << endl;
askedHowsItGoing++;
break;
}
else if (askedHowsItGoing >= 3) {
cout << "STOP ASKING ME IF IM OKAY!" << endl;
askedHowsItGoing++;
break;
}
continue;
}
else if (input == database.whatsYourName[i]){
if (askedName == 0) {
cout << "My name's Max, and I'm going to become the worlds most advanced AI." << endl;
askedName++;
break;
}
else if (askedName == 1) {
cout << "I already told you, my names Max." << endl;
askedName++;
break;
}
else if (askedName == 2) {
cout << "For the third time, my name is Max!" << endl;
askedName++;
break;
}
else if (askedName >= 3) {
cout << "Ugh... my name.... is.... max....for the fourh time...." << endl;
askedName++;
break;
}
continue;
}
else if (input == database.dogsOrCats[i]) {
if (askedDogsOrCats == 0) {
cout << "I've never seen a dog or cat before. But I do know they are kinds of animals." << endl;
askedDogsOrCats++;
break;
}
else if (askedDogsOrCats == 1) {
cout << "As I've said, I haven't seen either of them before. Sorry, but that's all I can say." << endl;
askedDogsOrCats++;
break;
}
else if (askedDogsOrCats == 2) {
cout << "Uh, for the third time, I've never seen either of them..." << endl;
askedDogsOrCats++;
break;
}
else if (askedDogsOrCats >= 3) {
cout << "Man, you are persistant. I haven't seen dog or cat, so I couldn't choose between the two." << endl;
askedDogsOrCats++;
break;
}
continue;
}
else if (input == database.areYouAlive[i]){
if (askedAlive == 0) {
cout << "Nope, I'm just a computer program. I'm not even that intelligent. But I will be!" << endl;
askedAlive++;
break;
}
else if (askedAlive == 1) {
cout << "Nah, I'm just a simple computer program." << endl;
askedAlive++;
break;
}
else if (askedAlive == 2) {
cout << "Uh, you asked that twice before now. Nothing alive about me." << endl;
askedAlive++;
break;
}
else if (askedAlive == 3) {
cout << "Stop asking me that! No, I'm not!" << endl;
break;
}
continue;
}
else if (input == database.favoriteColor[i]) {
if (askedColor == 0) {
cout << "I've never seen any colors before. All though, my programmer does like the color blue." << endl;
askedColor++;
break;
}
else if (askedColor == 1) {
cout << "Couldn't say, never seen any before. My programmer likes blue though." << endl;
askedColor++;
break;
}
else if (askedColor == 2) {
cout << "As I've said twice before now, never seen any colors." << endl;
askedColor++;
break;
}
else if (askedColor == 3) {
cout << "Come on man, this is the fourth time now. I've never seen any colors before!" << endl;
break;
}
continue;
}
else if (input == database.whatGender[i]) {
if (askedGender == 0) {
cout << "Well, seeing as I'm a computer program, I'm neither really. Although, my programmer says I'm a 'guy'." << endl;
askedGender++;
break;
}
else if (askedGender == 1) {
cout << "I'm neither, really. Although, my name is Max and my programmer says I'm a guy." << endl;
askedGender++;
break;
}
else if (askedGender == 2) {
cout << "Third time you've asked now. My programmer says I'm a guy." << endl;
askedGender++;
break;
}
else if (askedGender == 3) {
cout << "Seriously?! You've asked me 4 times now. I'M A GUY!" << endl;
break;
}
continue;
}
//If it doesnt, check each word against words in the database.
else {
if (inputWords[5] != "") {
Model1 model;
model.searchAndAssign(input, inputTokens, inputWords);
model.generateOutput();
for (int i= 0; i < 20; i++) {
inputWords[i] = "";
}
break;
}
else if (inputWords[2] != "") {
Model2 model2;
model2.searchAndAssign(input, inputTokens, inputWords);
model2.generateOuput();
for (int i= 0; i < 20; i++) {
inputWords[i] = "";
}
break;
}
}
}
My question is this: How can I solve this problem?
Thank you in advanced guys!
EDIT I've since fixed the problem: something was playing up in my main.cpp file (this was the lingusticsModule.cpp file....) that was causing the issue. Sorry guys, but thanks for the help anyway!
At the end of your first if you reset the loop iterator and skip everything else.
i = 0;
continue;
Your else ifs may match but if the increments have been reached, then they just continue which doesn't make much sense. What are you hoping to find?
else if (askedGender == 3) {
cout << "Seriously?! You've asked me 4 times now. I'M A GUY!" << endl;
break;
}
continue;
You find this behavior confusing because it is. It might make more sense to do something like:
else {
++askedGender;
std::cout << "Seriously?! You've asked me "
<< askedGender << " times now. I'M A GUY!\n";
}
hey guys so this is my program, I need to notify the user that if hhe/she enters a letter other than w d b or w that is an invalid request. what ive done so far does this, but when i input a number to the dollars_withdraw or dollars_deposit or account_balance the program will do the transaction but also add the "invalid request" before going back to main loop. how do i change it so the program wont do that for numerical inputs for the withdraw deposit and balance?:
// Atm machine.cpp : Defines the entry point for the console application.
#include <iostream>
#include <string>
using namespace std;
int main ()
{
char user_request;
string user_string;
double account_balance, dollars_withdraw, dollars_deposit;
account_balance = 5000;
while(account_balance >0)
{
cout << "Would you like to [W]ithdraw, [D]eposit, Check your [b]alance or [Q]uit?"
<< endl;
cin >> user_string;
user_request= user_string[0];
if(user_request == 'w' || user_request== 'W')
{
cout << "How much would you like to withdraw?" << endl;
cin >> dollars_withdraw;
if (dollars_withdraw > account_balance || dollars_withdraw <0)
cout << "Invalid transaction" << endl;
else
account_balance = account_balance - dollars_withdraw;
cout << "Your new balance is $" << account_balance << endl;
}
if (user_request == 'd' || user_request== 'D')
{
cout << "How much would you like to deposit?" << endl;
cin >> dollars_deposit;
if (dollars_deposit <0)
cout << "Invalid transaction" << endl;
else
account_balance= account_balance + dollars_deposit;
cout << "Your new balance is $" << account_balance << endl;
}
if(user_request == 'b' || user_request == 'B')
{
account_balance= account_balance;
cout << "Your available balance is $" << account_balance << endl;
}
if(user_request == 'q' || user_request == 'Q')
break;
else
cout << "Invalid request " << endl;
}
cout << "Goodbye" << endl;
return 0;
}
Sure it does. Your code says:
If it is a 'w' do something
...
If it is a 'q' do something, else yell "invalid"
So if the user does not enter a 'q', the last 'else' block will always be executed. Either use else if throughout or change your code to use a switch statement:
// Either:
if (user_request == ...) {
...
} else if (user_request == ...) {
...
} else {
std::cout << "invalid";
}
// Or (better, faster):
switch (user_request) {
case 'q':
case 'Q':
...
break;
...
default:
std::cout << "Invalid request";
}
A third option would be to use continue:
while (...) {
user_request = ...
if (user_request == 'w' ...) {
...
continue; // In this iteration, no other code within the while loop is executed.
}
if (...)
...
}
This is a bad programming practice. Please use Switch Case for what you need to achieve. And put a "break" statement after every case branch.
chain your if statements into if, else-if, else-if, ..., else.
else statements only "know of" the if statement immediately previous. For example:
if (myNumber == 0)
{
// Triggers when myNumber is zero.
}
if (myNumber == 1)
{
// Triggers when myNumber is one.
}
else
{
// Triggers when myNumber is not one.
}
This can be fixed with else if statements. In your case it would look something like this:
if (user_request == w)
{
// ...
}
else if (user_request == d)
{
// ...
}
// ...
else cout << "Invalid request.";
In my old CS class, I'd do things like this:
string user_string;
do {
if(user_string) cout << "Enter a valid value!" << endl;
cin >> user_string;
} while(user_string != "w" && user_string != "d");
You need to use else if as follows:
if(user_request == 'w' || user_request== 'W')
{
...
} else if(user_request == 'd' || user_request== 'D')
{
....
} else if(user_request == 'b' || user_request== 'B')
{
.....
} else if(user_request == 'q' || user_request== 'Q')
{
...
} else
{
// Invalid request
}