Me not understanding do while loops [closed] - c++

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
So i tried to make my first console aplication but it came to a bit of a bummer since i dont understand how a do while loop works
#include <iostream>
int balance = 100;
int pay = 30;
int awnser;
// Variables for the awnsers
int withdrawal;
int a = 1;
int main() {
do {
std::cout << "\n Whats the action you wanna do? \n 1 = Check balance \n 2 = Withdraw money \n 3 = Deposit money \n 4 = Check transaction history \n 5 = Exit \n";
std::cout << " ";
std::cin >> awnser;
if (awnser == 1) {
std::cout << balance << " Euros\n \n";
}
if (awnser == 2) {
std::cout << "How much do you wanna with draw?\n";
std::cin >> withdrawal;
if (withdrawal > balance)
std::cout << "You dont have that much money.\n \n";
else {
std::cout << "Your current balance is: " << balance - withdrawal;
}
}
if (awnser == 3) {
std::cout << "We know you dont have enymore daam money you beggar so dont even try that\n \n";
}
if (awnser == 4) {
}
if (awnser == 5) {
std::cout << "Enter 0 to exit or 1 to go back\n";
std::cin >> a;
}
else if (a == 1) {
std::cout << "\n";
return 1;
}
} while (a == 1);
}
I thought it would get back to the top since no other "if" requierements were met and just give me the "Whats the action you wanna take again" but it just exits out so what am i doing wrong?

If the number input isn't one that you check (1 to 5) then you hit:
else if (a == 1) {
std::cout << "\n";
return 1;
}
which will enter the if (because a is 1), print a new line and return from main ending your run.

Related

loops missing the nested if [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 9 months ago.
The community reviewed whether to reopen this question 9 months ago and left it closed:
Duplicate This question has been answered, is not unique, and doesn’t differentiate itself from another question.
Improve this question
My loop is skipping the nested 3rd else if. What should I do so it does not skip it?
#include <iostream>
int main()
{
int loop, i;
loop = 0;
char choice, selection;
std::cout << "Welcome" << std::endl;
while (loop == 0)
{
std::cout << "Please a choice" << std::endl;
std::cout << "a. Run" << std::endl;
std::cin >> selection;
if (selection == 'a')
{
for (i = 1; i < 5; i++)
{
std::cout << "run" << std::endl;
std::cout << "do you want to continue running? (y/n)";
std::cin >> choice;
if (i < 5 && choice == 'y')
{
continue;
}
else if (i < 5 && choice == 'n')
{
break;
}
else if ( i > 5 && choice == 'y')
{
std::cout << "Limit Reached";
}
}
}
I want it to print "limit reached" when i > 5, but somehow the loop skips it. What am I doing wrong?
Previous StackOverflow questions did not help much. I tried their solutions, but they did not solve my issue.
Edit:
For example: Nesting if statements inside a While loop? I have looked if I have initialized any of my int which might be messing my loop.
Looks like my else if didn't work because the condition I gave it would never be true. I feel stupid. But thanks everyone for your time. I really appreciate it.
Your loop runs only while i is in the range 1..4 inclusive, so i < 5 will always be true and i > 5 will never be true.
You should check the value of i after the loop exits. You should also check the user's input to make sure it matches your expectations.
Try something more like this:
#include <iostream>
#include <cctype>
bool shouldContinue(const char *prompt)
{
char choice;
do
{
std::cout << prompt << " (y/n)";
if (!(std::cin >> choice)) throw ...;
if (choice == 'y' || choice == 'Y' || choice == 'n' || choice == 'N') break;
std::cout << "Invalid choice" << endl;
}
while (true);
return (choice == 'y' || choice == 'Y');
}
int main()
{
bool loop = true;
int i;
char selection;
std::cout << "Welcome" << std::endl;
while (loop)
{
std::cout << "Please a choice" << std::endl;
std::cout << "a. Run" << std::endl;
std::cin >> selection;
if (selection == 'a')
{
for (i = 1; i < 5; ++i)
{
std::cout << "run" << std::endl;
if (!shouldContinue("do you want to continue running?"))
break;
}
if (i == 5)
std::cout << "Limit Reached";
}
...
}
return 0;
}

How can I get 2 integer values from one input? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I'm only in 10th grade and there is an exercise where I have to get an input like (input = 1/2) and this input needs to be stored in 2 different integers and I don't know how to do that.
Any help is appreciated.
Sorry if this question sounds dumb, but this is my first post here and I don't know the etiquette.
Thanks in advance!
Read two integers and ignore/match the character between them. The nicest way to match the character would be a manipulator:
std::istream& slash(std::istream& in) {
if ((in >> std::ws).peek() == '/') {
in.ignore();
}
else {
in.setstate(std::ios_base::failbit);
}
return *this;
}
int main() {
int numerator, denominator;
if (std::cin >> numerator >> slash >> denominator) {
std::cout << " read " << numerator << '/' << denominator << '\n';
}
}
Simply use the existing iostream functionality. There is nothing complicated about that. String parsing is not necessary. The inserter operator will skip whit spaces. Additionally, it will convert your given values into an integer variable. The slash will be read, checked and then discarded.
#include <iostream>
int main() {
int number1{}, number2{};
char slash{};
std::cout << "\nEnter a string: ";
if (std::cin >> number1 >> slash >> number2 && slash == '/') {
std::cout << "\n\nNumber 1: " << number1 << "\nNumber 2: " << number2 << "\n\n";
}
else {
std::cerr << "\nError: invalid input\n\n";
}
return 0;
}
Solution:
Take the input as a std::string and then parse it.
Full code:
#include <iostream>
std::pair<int,int> inputNumbers()
{
std::string input;
std::cout << "Input: ";
std::cin >> input;
size_t slashPos = input.find('/');
if(slashPos == input.npos || slashPos == 0 || slashPos == input.size() - 1)
{
std::cout << "Error! Please try again.\n";
exit(0);
}
std::pair<int,int> ret;
try
{
ret.first = std::stoi(input.substr(0,slashPos));
ret.second = std::stoi(input.substr(slashPos+1,input.size()-slashPos-1));
}
catch(std::invalid_argument&)
{
std::cout << "Error! Please try again.\n";
exit(0);
}
return ret;
}
int main() {
std::pair<int,int> inputs = inputNumbers();
std::cout << "First number: " << inputs.first << ". Second number: " << inputs.second << ".\n";
}

CODE is not executing in c++ [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 4 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
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.
Improve this question
TASK 2 remains un-executed. Task 1 works fine, I input the yield values of the cows; but then the code stops running. A warning says that Herdtotalweek may be uninitialized. But I don't know how to fix that. There are no other warnings or errors.
#include <iostream>
#include <string>
using namespace std;
int main() { //Task 1
int Herdsize;
int Day;
float MilkYield1;
float MilkYield2;
int count;
cout << "Please input herd size" << endl;
cin >> Herdsize;
while (Herdsize < 1 || Herdsize > 900) {
cout << "Please re-input herdsize between 1 and 900" << endl;
cin >> Herdsize;
}
int CowID[Herdsize + 1];
float DailyYield[Herdsize * 7];
float WeeklyYieldpercow[Herdsize * 14];
for (count = 1; count < Herdsize + 1; count++) {
cout << "Input 3 digit cow id ";
cin >> CowID[count];
while (CowID[count] < 1 || CowID[count] > 999) {
cout << "Please re-input cow a 3 digit cow id " << endl;
cin >> CowID[count];
}
for (Day = 1; Day < 8; Day++) {
cout << "Please input first milk yield of cow,day";
cout << Day;
cout << endl;
cin >> MilkYield1;
cout << "Please input second milk yield day:";
cout << Day;
cout << ", if there is a second yield if not enter 0";
cout << endl;
cin >> MilkYield2;
}
DailyYield[((count - 1) * 7) + Day] = MilkYield1 + MilkYield2;
WeeklyYieldpercow[count] = WeeklyYieldpercow[count] +
DailyYield[((count - 1) * 7) + Day];
}
// TASK 2
int count2 = 1;
float Herdtotalweek;
float Averagevolume;
for (count = 1; count2 < Herdsize + 1; count++) {
Herdtotalweek = Herdtotalweek + WeeklyYieldpercow[count];
}
Averagevolume = Herdtotalweek / Herdsize;
int Herdtotalweekwhole = int(Herdtotalweek + 0.5);
int Averagevolumewhole = int(Averagevolume + 0.5);
cout << "Total weekly volume=";
cout << Herdtotalweekwhole;
cout << "Average volume =";
cout << Averagevolumewhole;
}
instead of float Herdtotalweek; try using float Herdtotalweek = 0; ?
also, in your second for statement, instead of for (count=1;count2<Herdsize+1;count++) try for (count=1;count<Herdsize+1;count++) (you were using count2 instead of count, which was probably a copy/paste error)
The for loop after task2 never completes. It is an infinite loop as you are not updating count2.

Random letter generator game [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 5 years ago.
Improve this question
Warning: I am brand new to programing! I am trying to create a random letter generator game for a class project. I feel like I have a decent start to it but I am having difficulty with a few points.
The program is supposed to ask the player how many games they would like to play(1-5). The maximum number of guesses they get per game is 5 and then it is supposed to print out what the correct answer was if it was not guessed. As it is, I have it so that it will run the correct number of guesses but not games and it dosent cout<< the correct answer when all guesses are done. Any help is appreciated, thanks.
#include<iostream>;
#include<cstdlib>;
#include<ctime>;
using namespace std;
int main()
{
char alphabet [27];
int number_of_games;
char guess;
int x = 1;
srand(time(0));
int n = rand() % 26 + 1;
cout<<"Weclome to the Letter Guessing game!\n";
cout<<"You have 5 chances to guess each letter.\n \n";
cout<<"How many games do you want to play?\n";
cin >> number_of_games;
cout<<"**************************************************\n\n";
while (x <= number_of_games) //Need to get it for how many rounds, not how many guesses
{
if (number_of_games < 1)
{
cout<< "Lets play game " << number_of_games << '\n';
}
//cout << (char)(n+97); //cheat to make sure working
cout<<"Enter your guess: ";
cin >> guess;
int guessValue = int(guess);
if (guessValue > (n+97))
{
cout<<"The letter you are trying to guess is before " <<guess <<"\n";
}
else if (guessValue < (n+97))
{
cout<<"The letter you are trying to guess is after " <<guess << "\n";
}
else if( (char)(n+97))
{
cout << "The answer you were looking for was " << (char)(n+97) << "\n";
}
else
{
cout<<"Your guess is correct! \n";
break;
}
//if answer is not right after x tries, cout the correct answer
x++;
}
system("pause");
return 0;
}
You can use "nested loops" - an outer loop for games, and an inner loop for turns. I've used a for loop in my example.
Also, no need to convert everything to int. char is an integral type and can be used just like a number:
while (x <= number_of_games) //Need to get it for how many rounds, not how many guesses
{
// Select a new char (a-z) for each game
char n = 97 + rand() % 27;
cout << "Lets play game " << x << '\n';
// 5 guesses
for (int number_of_guesses = 0; number_of_guesses < 5; number_of_guesses++) {
cout << "Enter your guess: ";
cin >> guess;
if (guess > n)
{
cout << "The letter you are trying to guess is before " << guess << "\n";
}
else if (guess < n)
{
cout << "The letter you are trying to guess is after " << guess << "\n";
}
else
{
cout << "Your guess is correct! \n";
// Break out of the inner for loop, not the while
break;
}
}
x++;
}

C++ while loop not starting [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
So the idea is to ask the user for each element of the array, but after an input is given for the first question (where it asks for the amount of elements), nothing happens. Can't figure out why.
#include <iostream>
int main()
{
int numGrades;
tryAgain:
std::cout << "Enter number of grades" << std::endl;
std::cin >> numGrades;
if (numGrades > 30)
{
std::cout << "Please enter a valid number of grades" << std::endl;
goto tryAgain;
}
int grades[numGrades - 1];
int gradeCount = 0;
while (gradeCount < numGrades);
{
std::cout << "Enter grade number" << gradeCount + 1 << ":";
std::cin >> grades[gradeCount];
++ gradeCount;
}
std::cout << grades;
return 0;
}
The constuction while (true); means while (true) {} (i.e. infinite loop).
So, when you write
while (gradeCount < numGrades);
{
// ...
}
you have the following:
while (gradeCount < numGrades)
{
}
{
// ...
}
Second block will never be executed if gradeCount < numGrades.
You are using
while (gradeCount < numGrades);
with a semi-colon (;) at the end of this line so the next line will not exectue because the condition is always true as there is no increment or decrement in the respective variables.
In short just remove the (;)
while (gradeCount < numGrades)
Please see this code, there were few problems. One is semicolon on while loop & another one is printing grades & memory allocation of the grades. Memory static allocation must need a constant value. Here a dynamic allocation is added as the grades number is not fixed or constant... Here is the code:
#include <iostream>
int main()
{
int numGrades;
tryAgain:
std::cout << "Enter number of grades" << std::endl;
std::cin >> numGrades;
if (numGrades > 30)
{
std::cout << "Please enter a valid number of grades" << std::endl;
goto tryAgain;
}
int *grades = (int *)malloc(numGrades * sizeof(int)); //allocating dynamic memory
int gradeCount = 0;
while (gradeCount < numGrades)
{
std::cout << "Enter grade number" << gradeCount + 1 << ":";
std::cin >> grades[gradeCount];
++ gradeCount;
}
for(int i =0;i<numGrades;i++)
{
std::cout << grades[i] << std::endl;
}
free(grades);//releasing memory
return 0;
}