I want the program to keep asking for values to do calculations until the flag is true then the program must stop, but it only ever executes once. I don't know if I am using the char the right way or if there is a better way to do these types of while loops with flags. Any help would be great.[enter image description here][1]
int main()
{
displayMenu();
bool flag = false;
while(!flag)
{
int choice = 0; int val1 = 0; int val2 = 0; int ans = 0;
cout << "Enter your choice (1-5): ";
cin >> choice;
cout << "\nEnter integer 1: ";
cin >> val1;
cout << "\nEnter integer 2: ";
cin >> val2;
if(choice < 0 || choice > 5)
{
cout << "\nEnter a choice between 1-5: ";
cin >> choice;
}
if (choice == 1)
{
ans = Add(val1,val2);
cout << "\nResult: " << ans << endl;
}
if (choice == 2)
{
ans = Subtract(val1,val2);
cout << "\nResult: " << ans << endl;
}
if (choice == 3)
{
ans = Multiply(val1,val2);
cout << "\nResult: " << ans << endl;
}
if (choice == 4)
{
ans = Divide(val1,val2);
cout << "\nResult: " << ans << endl;
}
if (choice == 5)
{
ans = Modulus(val1,val2);
cout << "\nResult: " << ans << endl;
}
char c_flag[] = "n";
cout << "Press Y or y to continue: ";
cin >> c_flag;
if(c_flag == "y" || c_flag == "Y")
{
flag = false;
}
else
{
flag = true;
}
}
return 0;
}
With data type char c_flag[], condition c_flag == "y" will very likely never be met, because you are comparing two (different) pointer values, not their contents.
Use std::string c_flag instead, and at least your conditions should work as expected.
You could also write
char c_flag[] = "y";
...
if (strcmp(c_flag,"y")==0) ...
but I'd prefer the std::string-variant for following reason: with char c_flag[] = "y", you allocate an array of size 2 (including string termination character); With cin >> c_flag, if you enter more than one character, you will exceed array length and yield undefined behaviour. With std::string, in contrast, the variable will "grow" if necessary.
Related
This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
Why must type getline(cin, string) twice?
(5 answers)
Closed 9 months ago.
what's wrong
if I use the get line function only once in the character modifier function the compiler will ignore it
unless I call the function twice
why cant I use it only once?
I tried using other ways, it worked but I wanna understand this one
I'm now just writing random things so the add more details error messages go away
#include <iostream>
#include<string>
using namespace std;
class egybest
{
string link,m;
char sys, type, restart;
int s = 1, e = 1, date;
public:
string charmodifier()
{
//here
getline(cin, m);
getline(cin, m);
for (int x = 0; x <= m.size(); x++)
{
if (m[x] == ' ')
m[x] = '-';
}
return m;
}
~egybest()
{
system("cls");
cout << "do you want to restart the program? y:n;" << endl;
cin >> restart;
system("cls");
if (restart == 'y' || restart == 'Y')
egybest();
else if (restart == 'n' || restart == 'N')
{
system("exit");
}
}
egybest()
{
cout << "do you want to watch a movie or a series? 1:2;" << endl;
cin >> type;
system("cls");
if (type == '1')
linkmovie();
else if (type == '2')
series();
else
cout << "wrong input!" << endl;
}
void linkmovie()
{
cout << "enter the name of the movie:" << endl;
charmodifier();
cout << "enter the release date: " << endl;
cin >> date;
link = "start https://cape.egybest.cool/movie/" + m + "-" + to_string(date);
cout << endl;
system(link.c_str());
}
void series()
{
cout << "do you want it to open links for a particular season, particular episode or all seasons? s:e:a;"
<< endl;
cin >> sys;
system("cls");
if (sys == 'S' || sys == 's')
linkseason();
else if (sys == 'A' || sys == 'a')
linkall();
else if (sys == 'E' || sys == 'e')
linkepisode();
else
cout << "wrong input!" << endl;
}
void linkall()
{
cout << "season No." << endl;
cin >> s;
cout << "episode No." << endl;
cin >> e;
cout << "enter the name of the show:" << endl;
charmodifier();
for (int j = 1; j <= s; j++)
{
for (int i = 1; i <= e; i++)
{
link = "start https://cape.egybest.cool/episode/" + m + "-season-" + to_string(j) + "-ep-" + to_string(i);
system(link.c_str());
}
}
cout << endl;
}
void linkepisode()
{
cout << "season No." << endl;
cin >> s;
cout << "episode No." << endl;
cin >> e;
cout << "enter the name of the show:" << endl;
charmodifier();
link = "start https://cape.egybest.cool/episode/" + m + "-season-" + to_string(s) + "-ep-" + to_string(e);
cout << endl;
system(link.c_str());
}
void linkseason()
{
cout << "season No." << endl;
cin >> s;
cout << "episodes No." << endl;
cin >> e;
cout << "enter the name of the show:" << endl;
charmodifier();
for (int i = 1; i <= e; i++)
{
link = "start https://cape.egybest.cool/episode/" + m + "-season-" + to_string(s) + "-ep-" + to_string(i);
cout << endl;
system(link.c_str());
}
}
};
int main()
{
egybest egy;
return 0;
}```
The problem is that after entering an integer or a character as for example
cout << "episode No." << endl;
cin >> e;
cout << "enter the name of the show:" << endl;
charmodifier();
//...
the input buffer contains the new line character '\n' that corresponds to the pressed Enter key.
So the following call of getline reads an empty string until the new line character is encountered.
In such a case before calling getline you need to remove the new line character from the input buffer like for example
#include <limits>
//...
cout << "episode No." << endl;
cin >> e;
cout << "enter the name of the show:" << endl;
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
charmodifier();
//...
So I've been getting: Warning C4244 '=': conversion from 'double' to 'long', possible loss of data line 158. From what I understand is that 'pow' and 'long int result' are somehow connected to this, I have been messing around with it and changed 'long int result' to 'double result' and got rid of the warning. I have a solution to get rid of the warning, but it won't matter since this program need long int to handle more data otherwise it will overflow if I use double.
If I decided to keep this warning in the program will there be potenial issues with it?
Can I somehow get rid of the warning and still be able to use 'long int result' or at least be able to handle more data some other way?
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
char menu, choice;
int numberYears = 0;
long int deposit, withdraw;
long int result = 0;
long int annualDeposit = 0;
float interestRate = 0.0;
long int balance = 0;
cout << "------------------------------\n" << "Welcome to Bank Simulator 3000" << "\n------------------------------\n\n";
while (true)
{
cout << "XXXXXXX[MENU]XXXXXXXX\n";
cout << "[D]eposit\n";
cout << "[W]ithdrawal\n";
cout << "[B]alance\n";
cout << "[I]nterest payment\n";
cout << "[E]xit\n";
cout << "XXXXXXXXXXXXXXXXXXXXX\n";
cin >> menu;
switch (menu)
{
case'd':
case'D':
cout << "\n[DEPOSIT]\n";
cout << "Do you want to make a deposit?\n" << "Y/N\n";
cin >> choice;
if (choice == 'Y' || choice == 'y')
{
cout << "\nHow much do you want to deposit?\n" << "\n:";
}
else
{
cout << "\nReturning to menu.\n\n";
continue;
}
cin >> deposit;
balance += deposit;
cout << "\n" << deposit << " Kr has been added to balance.\n\n";
continue;
case'w':
case'W':
cout << "\n[WITHDRAWAL]\n" << "Do you want to make a withdrawal?\n" << "Y/N\n";
cin >> choice;
if (choice == 'Y' || choice == 'y')
{
cout << "\nHow much do you want to withdraw?\n" << "\n:";
}
else
{
cout << "\nReturning to menu.\n\n";
continue;
}
cin >> withdraw;
if (withdraw == 0)
{
cout << "\nYou withdrew 0 amount. No changes will apply.\n\n";
continue;
}
balance -= withdraw;
cout << "\n" << withdraw << " Kr has been drawn from balance.\n\n";
continue;
case'b':
case'B':
cout << "\n[BALANCE]\n";
cout << balance << " Kr\n\n";
continue;
case'i':
case'I':
cout << "\n[INTEREST PAYMENT]\n";
cout << "Do you want to calculate your interest payment?\n" << "Y/N\n";
cin >> choice;
if (choice == 'Y' || choice == 'y')
{
cout << "What's your annual deposit?\n" << ":";
}
else
{
cout << "\nReturning to menu.\n\n";
continue;
}
cin >> annualDeposit;
if (annualDeposit == 0)
{
cout << "You typed 0 in your annual deposits, this will give unwanted results.\n" << "Do you want to continue?\n" << "Y/N\n";
cin >> choice;
if (choice == 'Y' || choice == 'y');
else
{
cout << "Returning to menu.\n\n";
continue;
}
}
cout << "What's Your Interest Rate?\n" << ":";
cin >> interestRate;
if (interestRate == 0)
{
cout << "You typed 0 in your interest rate, this will give unwanted results.\n" << "Do you want to continue?\n" << "Y/N\n";
cin >> choice;
if (choice == 'Y' || choice == 'y');
else
{
cout << "Returning to menu.\n\n";
continue;
}
}
cout << "How many years do you want to save to?\n" << ":";
cin >> numberYears;
if (numberYears <= 0)
{
cout << "You typed 0 or less in number of years, this will give unwanted results.\n" << "Do you want to continue?\n" << "Y/N\n";
cin >> choice;
if (choice == 'Y' || choice == 'y');
else
{
cout << "Returning to menu.\n\n";
continue;
}
}
result = annualDeposit * pow(1 + interestRate / 100, numberYears);
cout << "Your Interest Payment Will Be: " << result << " Kr In " << numberYears << " Years\n\n";
continue;
default:
cout << "\nPlease use the following example\n" << "D = Deposit | W = Withdrawal | B = Balance | I = Interest payment | E = Exit\n\n";
continue;
case'e':
case'E':
cout << "Thanks for using Bank Simulator 3000!\n";
cout << "Press any key to close";
system("pause>0");
break;
}
break;
}
return(0);
}
In typical environment, a double variable can store a floating-point number upto about 10^300 (assuming IEEE754 64-bit is used).
On the other hand, a long int can store an integer only upto about 10^9 (32-bit) or 10^18 (64-bit).
Therefore, the maximum value to handle by long int is much smaller than one for double. This is why conversion from double to long int can cause loss of data.
You can add an explicit cast to suppress the warning.
result = static_cast<long int>(annualDeposit * pow(1 + interestRate / 100, numberYears));
The issue that I'm having is that if you input any string the cin will assign the int to 0. An interesting finding is that if you later take cin to a string you get the entire string you put in for the int. cin.fail() always returns true for some reason, even with cin.ignore(), etc and if( cin >> startingPosition ) also always returns true. So, how do I get it to catch an even recognize that it's a string and not an int? As in, how do I have it loop again if it is a string?
int getUserPosition(bool volatileCall = false) {
cout << "Which slot do you want to drop the chip in (0-8)? " << endl;
int startingPosition;
cin >> startingPosition;
while (startingPosition >= WIDTH || startingPosition < 0) {
cout << "Invalid slot." << endl << endl;
if (volatileCall) {
return -1;
}
cout << "Which slot do you want to drop the chip in (0-8)? " << endl;
cin >> startingPosition;
cout << startingPosition << endl;
}
return startingPosition;
}
you must save result from cin
isNumber = (cin >> startPosition);
the whole code will look like
int getUserPosition(bool volatileCall = false) {
cout << "Which slot do you want to drop the chip in (0-8)? " << endl;
int startingPosition;
bool isNumber = (cin >> startingPosition);
while(isNumber && (startingPosition >= WIDTH || startingPosition < 0)) {
cout << "Invalid slot." << endl << endl;
if (volatileCall) {
return -1;
}
cout << "Which slot do you want to drop the chip in (0-8)? " << endl;
isNumber = (cin >> startingPosition);
cout << startingPosition << endl;
}
return startingPosition;
}
I am attempting to create a program that can print ascii art letters when given J, E, or C and the size (7 or greater and an odd number). I have been able to successfully run the program until I added a Y/N response prompt. I would like to ask the user if they would like to continue, if yes, then I would like to restart the loop. However, I'm trying to write the code to meet the conditions of if they enter 'e' then 'e' ascii art prints, if they enter 'c' then ascii art prints, etc. However, I cannot figure out how to restart the loop and accept new information.
Also, my current predicament is that the do loop is not meeting with my last while loop for a 'No' response. I'm new to C++ and would appreciate any help that can be provided. Thank you!
#include <iostream>
using namespace std;
int main() {
int s;
char l;
char choice;
cout << "Welcome to the letter printer." << endl;
do {
cout << "Enter the size: " << endl;
cin >> s;
while (s < 7 || s % 2 == 0 || s < 0) {
cout << "Invalid size. Enter the size again: " << endl;
cin >> s;
}
cout << "Enter the letter: " << endl;
cin >> l;
while (l != 'c') {
cout << "Invalid letter. Enter the letter again: " << endl;
cin >> l;
}
if (l == 'c') {
int size = s;
for (int row = 0; row < size; row++) {
cout << "*";
for (int col = 0; col < size - 1; col++) {
if (row == size - 1)
cout << "*";
else
cout << " ";
if (row == 0)
cout << "*";
else
cout << " ";
}
cout << endl;
}
}
} while (choice == 'N');
return 0;
}
You're using choice without reading into it. Additionally, the check while (choice == 'N') doesn't make sense, you want to continue while the choice is no?
Here's the gist of it with the irrelevant parts cut for brevity.
#include <iostream>
int main() {
char choice{};
std::cout << "Welcome to the letter printer.\n";
do {
int s{};
std::cout << "Enter the size: " << std::flush;
std::cin >> s;
// ... check for size ...
char l{};
std::cout << "Enter the letter: " << std::flush;
std::cin >> l;
// ... check for letter ... draw letter ...
std::cout << "would you like to continue? (Y/N): " << std::flush;
std::cin >> choice;
} while (choice == 'Y');
}
For future reference, most of the code in your question isn't directly relevant to the problem, the restrictions on what letters to enter, the size restriction, and the drawing of the letter could all be left out when making your example. Doing this tends to reveal the problem.
I have fixed your code and in the meantime I want to make a few remarks for the future.
Before posting to StackOverflow asking for debugging, debug it yourself. I understand sometimes you may have a sore head from looking at the same code for a long time but not everyone likes debugging code here.
Have some decency and post code that is at the least functioning to some degree. It is a complete pain trying to find curly braces, commas, etc. that you should have found yourself.
Next time isolate your problem in your code before posting it here.
Regarding your code, you were thinking in the right direction.
In while(choice == 'N') [As pointed out by Raindrop7 & Ryan Haining], your char choice was undeclared. Simple fix is to declare / use the variable like cin >> choice in the example below.
Name your variables with sense, it s hard to keep track of a variable when it is being used everywhere e.g. [char s, int l].
Encapsulate code if it is being reused a lot e.g. [void PrintLetter(char, int)]
Side Note: Next time you encounter a bug. Put some kind of animal toy beside you and speak your problem out to it. Usually you'll answer your own question.
#include "stdafx.h"
#include <iostream>
using namespace std;
void PrintLetter(char letter, int size)
{
switch (letter)
{
case 'c':
for (int row = 0; row < size; row++)
{
cout << "*";
for (int col = 0; col < size - 1; col++)
{
if (row == size - 1)
{
cout << "*";
}
else
{
cout << " ";
}
if (row == 0)
{
cout << "*";
}
else
{
cout << " ";
}
cout << endl;
}
}
break;
case 'f':
break;
case 'l':
break;
}
}
int main() {
int size;
char letter;
char choice;
cout << "Welcome to the letter printer." << endl;
do {
cout << "Enter the size: " << endl;
cin >> size;
while (size < 7 || size % 2 == 0 || size < 0) {
cout << "Invalid size. Enter the size again: " << endl;
cin >> size;
}
cout << "Enter the letter: " << endl;
cin >> letter;
while (letter != 'c') {
cout << "Invalid letter. Enter the letter again: " << endl;
cin >> letter;
}
PrintLetter(letter, size); // Print Letter In Here, Function At The Top
cout << "Would you like to continue? [Y,N]" << endl;
cin >> choice;
}while (choice == 'Y' || choice == 'y'); // End Do While
return 0;
} // End Main
This is a menu driven program for calculations.
#include <iostream>
#include <cmath>
using namespace std;
void Choices();
int x;
int n;
float fact;
float cosh(float x, int n);
float sinh(float x, int n);
float factorial( int n );
int main ()
{ char exit;
char choice;
bool option1hasrun = false;
while (exit != 'y' || exit != 'Y')
{
Choices();
cin >> choice;
if (choice == '1' && option1hasrun == false) {
cout << "Please give a value for x: ";
cin >> x;
cout << "Please give a value for the approximation order n: ";
cin >> n;
cout << endl;
option1hasrun = true;
}
else if (choice == '2' && option1hasrun == true)
{
cout << "The hyperbolic sinh of x is: " << sinh(x) << endl;
cout << "Using Taylor series is it: " << sinh(x, n) << endl;
}
else if (choice == '3' && option1hasrun == true)
{
cout << "The hyperbolic cosh of x is: " << cosh(x) << endl;
cout << "Using Taylor series is it: " << cosh(x, n) << endl;
}
else if (choice == '4' && option1hasrun == true)
{
cout << "old value of x = " << x << endl;
cout << "old approximation = " << n << endl;
cout<< "Please give new value of x: " ;
cin >> x;
cout << endl;
cout << "Please give new n: " ;
cout << endl;
cin >> n;
}
if ((choice=='2' || choice=='3' || choice=='4') && option1hasrun==false)
{
cout << "You have to enter a value first!\n\n";
}
if (choice<'0' || choice > '4')
{
cout << "Wrong choice. Only options 1-4 are available.\n\n";
}
else if (choice == '0' && option1hasrun==true)
{
cout << "Are you sure you want to quit? (Y/N) ";
cin >> exit;
if (exit =='y' || exit == 'Y') {
cout << "bye bye!!";
}
}
/* After entering Y I would like the program to stop, but currently it continues to loop*/
}
return 0;
}
float factorial( int n )
{
float fact = 1;
for ( int i = 1; i <= n; i++ )
{
fact = fact * i;
}
return fact;
}
float sinh(float x, int n)
{
float sum = 0;
for ( int i = 0; i <= n; i++ )
{
sum = sum + pow(x, 2*i +1)/factorial(2*i +1);
}
return sum;
}
float cosh(float x, int n)
{
float sum = 0;
for ( int i = 0; i <= n; i++ )
{
sum = sum + pow(x, 2*i)/factorial(2*i);
}
return sum;
}
void Choices ()
{
cout << "MAIN MENU" << endl;
cout << "1. To enter the data. " << endl;
cout << "2. To calculate and approximate the sinh(x)" << endl;
cout << "3. To calculate and approximate the cosh(x) " << endl;
cout << "4. To modify data. " << endl;
cout << "0. to quit." << endl << endl;
cout << "Please make a choice :";
}
Can someone help me figure out why the program continue to loops after choice 0?
Entered characters cannot be neither 'y' nor 'Y' at the same time.
Try changing the exit condition to:
while (exit != 'y' && exit != 'Y')