Unexpected output in cout [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 8 years ago.
Improve this question
So, this is my very first questions on Stack Overflow. I'm in the process of learning C++ after some hard-fought experience with MATLAB. I've got a simple exercise that builds fine, but does not produce the expected result.
I get no errors, either. I'm running Xcode 5.
I suspect the problem has something to do with the initialization of my variables. When I look into debugging, my variables stay set to 0.
#include <iostream>
using namespace std;
int main()
{
//Declare variables
int score = 0;
//input score
cout << "Emter score: ";
cin >> score;
if (score == 100)
{
cout << "Final Score: " << score;
cout << "You received a perfect score! \n";
// 100% is an A.
}
else if ((score >= 90) && (score <= 100))
{
cout << "Final Score: " << score;
cout << "Your grade is an A. Nice Job! \n";
// 90-100 is an A.
}
else if ((score >= 80) && (score <= 89))
{
cout << "Final Score: " << score;
cout << "Your grade is a B. Well done. \n";
// 80-89 is a B.
}
else if ((score >= 70) && (score <= 79))
{
cout << "Final Score: " << score;
cout << "Your grade is a C. Really? \n";
// 70-79 is a C.
}
else if ((score >= 60) && (score <= 69))
{
cout << "Final Score: " <<score;
cout << "Your grade is a D. You suck. Seriously. \n";
// 60-69 is a D.
}
else if ((score >= 0) && (score <= 59))
{
cout << "Final Score: " << score;
cout << "You got an F! YOU FAIL! GO JUMP OUT THE WINDOW. \n";
// 0-59 is an F.
}
return 0;
}
Sorry for the long post, I did not want to leave anything out. Thanks again.
ETA: Fixed the newline characters. I retyped the code in line for line and it ran just fine. I suspect it had something to do with the way all this stuff was being cast, but I'm not sure.

Welcome to SO, and to C++!
This issue may all come down to a simple typo - where you've used the newline character, you've typed a forward (instead of back-) slash; the correct newline character is \n.
There is actually another method for outputting the newline character as follows:
cout << endl;
which is the method I would recommend, at least for now, while you have no reason to choose one over the other. Others disagree however, and would advocate the use of \n. The difference between the two is that endl performs a flush, while \n does not (and /n certainly does not!) - at least not as standard.
If all this flush talk sounds like I've gone potty - just ignore it, stick to endl (unless you're on a course where your instructor has specified to use \n), and you'll no doubt encounter more about buffers and flushing soon!
Assuming your "unexpected output" was "everything is on the same line and it says '/n' everywhere" - this is all you need do to fix (you can go ahead and remove those '/n's).
NB: The reason for /n vs \n is that \ is the escape character - that is, whatever follows it is said to be escaped. Thus in the newline character, \n, n is escaped, and we do not see an 'n' displayed in cout.
But that does not mean that the n is not important! Together with \ it forms a single ASCII character (single will be important later, when you begin manipulating variables of the char type) to print a new line. Conversely, / is not the escape character, so when you used /n you saw both / and n displayed.

I cleaned up your code some and made note of some common practices that may be helpful to know. Also, as the previous answer mentioned the most likely cause of your problem was the newline character. Welcome the wonderful world of c++!
include
using namespace std;
int main()
{
//Declare variables
double score = 0; //this should really be a double if we are talking about grades
//input score
cout << "Enter score: ";
cin >> score;
cout << "Final Score: " << score << endl; //endl is the more common line ending that I've seen
// with my experience in C++
cout << "Your grade is a"; //you can remove all commonalities between if
// statements to save yourself some typing
// This is also common practice
if (score == 100)
{
cout << " perfect score!" << endl;
// 100% is an A.
}
else if (score >= 90 && score < 100) //we use < 100 instead of <= 99 because what about
// numbers between 99 and 100
{
cout << "n A. Nice Job!" << endl;
// 90-100 is an A.
}
else if (score >= 80 && score < 90)
{
cout << " B. Well done." << endl;
// 80-89 is a B.
}
else if (score >= 70 && score < 80)
{
cout << " C. Really?" << endl;
// 70-79 is a C.
}
else if (score >= 60 && score < 70)
{
cout << " D. You suck. Seriously." << endl;
// 60-69 is a D.
}
else //if we are not handling errors (assuming user
// enters 0 to 100), we can just say else
{
cout << "n F! YOU FAIL! GO JUMP OUT THE WINDOW." << endl;
// 0-59 is an F.
}
return 0;
}

Related

Identifier response is undefined and expected a ; [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 1 year ago.
Improve this question
In my c++ course, I have been asked to generate a random number between 1 and 12 and add it to a sum. The program will ask if the user wants to add another number with the input y or n, and if the input is y it will add another number. When the sum reaches 50, the program will automatically end.
However, on lines 14 and 27, I get the error:
Expected a ;
And on line 16 I get the error:
identifier response is undefined
#include <iostream>
#include <iomanip>
using namespace std;
void rng(){
int rng = ((rand() % 12) + 1);
cout << rng;
}
int main()
{
int sum = 0
char response;
cout << "Would you like to add a number? y or n";
cin << response;
while (response = 'y') {
cout << "Would you like to add a number? y or n";
cin << response;
cout << "Okay then, the current sum is" << +" " << +sum << +rng;
if (response = 'n')
cout << "Okay thanks, have a good one";
if (sum > 50)
cout << "Alright the sum has reached 50 that seems like enough"
break
};
}
There are a number of mistakes in your code - some related to syntax errors, and some related to logic issues.
Regarding the syntax errors:
int sum = 0
needs to be
int sum = 0;
A semicolon ends a statement.
cin << response;
needs to be
cin >> response;
operator<< is used for output, whereas operator>> is used for input.
cout << "Okay then, the current sum is" << +" " << +sum << +rng;
needs to be
cout << "Okay then, the current sum is " << sum;
Using + on sum is redundant, but using + on rng is just plain wrong, since rng is a function, not a variable.
cout << "Alright the sum has reached 50 that seems like enough"
needs to be
cout << "Alright the sum has reached 50 that seems like enough";
Again, a semicolon ends a statement.
break
needs to be
break;
Again, a semicolon ends a statement.
Regarding the logic issues:
there is no need for #include <iomanip>, as you are not utilizing any stream manipulators.
you are missing #include <cstdlib> for rand().
rng() is a function, but the statement cout << ... << +sum << +rng; is trying to print it out as if it were a variable instead. The project requirement is to add the random number to the running sum, so rng() should return the number it generates, and then main() can add that number to sum before printing it out.
you are not calling srand() to initialize the random number generator before calling rand() the 1st time.
while (response = 'y') needs to be while (response == 'y'). operator= is for assignment, operator== is for comparison. That said, you should use a do..while loop instead, as there is no point in prompting the user twice on the 1st loop iteration.
if (response = 'n') needs to be if (response == 'n'). Again, assignment vs comparison. Also, you are also not break'ing the loop if the user enters 'n'.
if (sum > 50) is missing {} braces, so the subsequent break is not part of the if, and thus it will be invoked unconditionally after the 1st loop iteration is done, so the user will never be able to enter more than 1 number.
your cout statements should have \n or std::endl at the end of them, to print out a line break.
With that said, try something more like this instead:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int rng(){
return (rand() % 12) + 1;
}
int main()
{
srand(time(NULL));
int sum = 0;
char response;
do {
cout << "Would you like to add a number? y or n: ";
cin >> response;
if (response == 'n') {
cout << "Okay thanks, have a good one\n";
break;
}
if (response == 'y') {
sum += rng();
cout << "Okay then, the current sum is " << sum << "\n";
if (sum > 50) {
cout << "Alright the sum has reached 50 that seems like enough\n";
break;
}
}
}
while (true);
}
This line:
int sum = 0
Needs a semi-colon at the end.
Same with these lines:
cout << "Alright the sum has reached 50 that seems like enough"
break
You need to use == instead of = in the condition of the while statement:
while (response == 'y') {
Also, this line:
cout << "Okay then, the current sum is" << +" " << +sum << +rng;
should be
cout << "Okay then, the current sum is" << " " << sum << rng;

While loop creating infinite loop

So I'm creating a program for a C++ class, and I created a while loop to stop invalid inputs.
Every time I do test it with an invalid input it goes into an infinite loop. I'm new to coding, so I really don't know how to fix it.
cout << "Enter weight in ounces (Max: 1800)" << endl;
cin >> pkgweight;
while (pkgweight > 0 || pkgweight < 1800)
{
cout << "Weight out of range. Program terminating.\n" << endl;
}
cout << "Enter miles shipping (Max: 3500)" << endl;
cin >> distance;
while (distance > 0 || distance < 3500)
{
cout << "Shipping distance out of range." << endl;
cout << "Program terminating.\n" << endl;
}
If nothing changes inside that loop, the exit condition will never be tripped.
Maybe you mean:
int pkgweight = 0;
cout << "Enter weight in ounces (Max: 1800)" << endl;
cin >> pkgweight;
if (pkgweight < 0 || pkgweight > 1800)
{
cout << "Weight out of range. Program terminating.\n" << endl;
}
You'll want to use while for situations where you want to loop until some condition is met. if is like a non-looping while.
While it's great that you're learning and it's understood you're going to make mistakes, slipping up on something this fundamental is usually a sign you don't have a good reference to work from. Get yourself a solid C++ reference book and refer to it often if you're ever stumped about something. This is essential for learning properly, not just picking up bits and pieces here and there and trying to intuit the gaps. Many parts of C++ will not make sense, they are artifacts of design decisions decades old and the influence of other programming languages you've never heard of. You need a proper foundation.
If you want the user to be able to fix an incorrectly entered input, you would want:
cout << "Enter weight in ounces (Max: 1800)" << endl;
cin >> pkgweight;
while (pkgweight > 0 || pkgweight < 1800)
{
cout << "Weight out of range. Program terminating.\n" << endl;
cout << "Enter weight in ounces (Max: 1800)" << endl;
cin >> pkgweight;
}
That way, if the user enters a number which is outside of the valid range, they will be prompted to enter a new number. If the new value is within the range, the loop will exit.
The problem with your current program is that a while loop will execute "while" the condition it checks for is true. In your current program, once pkgweight is set, it stays the same value. This means that if the loop is entered because the condition it checks for is true, that condition will never change (allowing the loop to exit), and your error message will be printed indefinitely.
Looking at your code, it seems like you want to kill the program if the input is wrong. You could consider terminating the function. Is this all in main()? If it is not in an external function, just do return -1. I know this is probably bad programming practice, but hey, it works specifically for this!
By the way, your conditional said > 0 and < 1800, which means the program will terminate if the variables distance and pkgweight are in the specified range.
Here is my working snippet without these errors, tested on onlineGDB.
#include <iostream>
using namespace std;
int main ()
{
int pkgweight, distance;
cout << "Enter weight in ounces (Max: 1800)" << endl;
cin >> pkgweight;
while (pkgweight < 0 || pkgweight > 1800)
{
cout << "Weight out of range. Program terminating.\n" << endl;
return -1;
}
cout << "Enter miles shipping (Max: 3500)" << endl;
cin >> distance;
while (distance < 0 || distance > 3500)
{
cout << "Shipping distance out of range." << endl;
cout << "Program terminating.\n" << endl;
return -1;
}
return 0;
}
Of course, instead of switching the less-than and greater-than, you could always wrap the conditional in a not operator.

while loop w/ 2 conditions does not work c++

I'm working on a minigame in C++ lately. The goal is to write a little game where you have to guesse a number. If you do so you'll get a point (I call it hit there) and if you don't you'll get a "miss". Logically speaking I don't want the game to go for ever. So I was trying to use a while loop to define at which scores you can still play. How you will be able to see in the code there are two conditions. Here is why I asked you: As long as there are two conditions it just ignores these so the game turns into an endless game. I don't recive any error-messages from VS2019. When I only try it w/ one condition it works just fine.
Here's the code:
#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
int main()
{
cout << "Welcom to the Hit-or-Miss-minigame. Here are the rules:" << endl;
cout << "You have to guess the same number as the computer. The numbers are within 0 and 10(both are still included)." << endl;
cout << "If you do so, you'll get a 'HIT' but if you don't you'll get a 'MISS'. When you reach 10 'HIT's you win" << endl;
cout << "but if you get a 'MISS' 15 times you'll lose." << endl;
char rep = 'y';
while (rep == 'y')
{
int hits = 0;
int miss = 0;
while ((hits < 3||miss < 15)) //Somehow doesn't work. So why?
{
int input_number;
srand(time(NULL));
int random_number = rand() % 11;
cout << "Your number: ";
cin >> input_number;
if (input_number == random_number)
{
cout << "HIT" << endl;
hits += 1;
}
else if (input_number != random_number)
{
cout << "MISS" << endl;
miss += 1;
}
else if ((input_number > 10) || (input_number < 0))
{
cout << "That was not an option";
}
else
{
cout << "That's not supposed to happen." << endl;
}
}
if (hits == 10)
{
cout << "You've won! Do you want to play another round?(y/n)" << endl;
cin >> rep;
}
else if (miss == 15)
{
cout << "You lose! Do you want to play another round?(y/n)" << endl;
cin >> rep;
}
}
}
I really would appreciate any help. Thanks!
EDIT: Problem solved. THANK YOU GUYS!
if you want the game will end after 3 hits or 15 misses you should use the && operator and not the || operator
it is because the || operator will return true when at least one of the conditions true, the && operator will return true when both of the true
Like the other comment said you should use && in your while loop, because you can have 16 misses and 3 hits before the loop breaks(for example 2 < 3 || 25 < 15 returns true and is only false when you get 3 < 3 || 25 < 15), which won't enter any if below the while, and it will just reset the variables back to 0 (this makes the while infinite). Furthermore if you put && in the while you need to change the if statement for hits to hits == 3 or it will never happen.
Also as a side note your if statement for numbers below zero and bigger than 10 needs to be above the one where you check if the guessed number is a miss (because every number bigger than 10 and smaller than 0 is a miss).
Hope this helps

How do I prevent program from running BOTH an IF and ELSE statement with C++?

#include <iostream>
#include <string>
int main()
{
int hun;
std::cout << "Please pick a number between 1 and 100 \n";
std::cin >> hun;
if (hun > 50)
{
std::cout << "Your number is greater than 50. ";
}
if (hun < 50)
{
std::cout << "Your number is less than 50. ";
}
if (hun > 100)
{
std::cout << "Pick a number LESS than 100. ";
}
else { std::cout << "Your number is equal to 50. "; }
return 0;
}
If I run it without the:
std::cout << "Pick a number LESS than 100. ";
then the program works as expected. However it doesn't work if I include it. For example if I input "13" I get both the message "Your number is less than 50, AND your number is equal to 50" ?? I don't understand why it is still executing the else statement if my IF statement was already met. This isn't an issue ONLY if I removes that 3rd IF statement.
I cannot figure out why it is just that line that is messing up. I seem to have everything written correctly, and I didn't forget the curly brackets. So why is this happening?
I'm sure it's a simple mistake. It's my first week coding and I'm doing it on my own with no outside help, so I don't have anyone to go to for silly questions like this.
While I'm here, how do I get the program to say something like "You have entered an invalid response. " When the user inputs a word or a letter? I thought about doing something like:
int word;
word = 1-100;
if (hun = word) or (hun != int?)
(But that will only subtract 100 from 1 giving me -99 and not the range, I really do not even know where to begin with this)
You need to implement if-else if- else statements:
if (hun > 100)
{
std::cout << "Pick a number LESS than 100. ";
}
else if (hun > 50)
{
std::cout << "Your number is greater than 50. ";
}
else if (hun < 50)
{
std::cout << "Your number is less than 50. ";
}
else
{
std::cout << "Your number is equal to 50. ";
}
The reason why the original code didn't work is that the else was only linked to the last if. So if a number satisfied one of the earlier if statements but not the last if it would go to both the if it satisfied and the else as the last if was not satisfied.
Additionally you must reorder it so that the more extreme cases are first. Otherwise if hun is more that one hundred but you have the condition hun > 50 then it will go to that if-else and then skip the rest.
Try this
if (hun >= 0 && hun < 50){
std::cout << "Your number is less than 50. ";
}
else if (hun == 50){
std::cout << "Your number is equal to 50. ";
}
if (hun > 50 && hun <= 100) {
std::cout << "Your number is less than 50. ";
}
else {
std::cout << "you ve entered invalid number " << hun << " . supported range is [0 - 100]";
}

I having issues with this program. Anyone seeing what I am doing wrong? Fairly new to this

Cannot get this run right. I having issues with this program. Anyone seeing what I am doing wrong? Fairly new to this. I have trying all day to get this right. and I am frustrated to no end right now. If anyone sees what I am doing wrong I would really appreciate it.
main ()
{
int adultTickets = 0, seniorTickets = 0, childTickets = 0, infantTickets = 0, baggage = 0, age = 0, passengerTotal = 0;
double totalBaggagefee = 0.0, baggageFee1 = 20.00, baggageFee2 = 35.00, adultFee = 147.30, seniorFee = 137.75, childFee = 110.25, infantFee = 0.0, totalTicket = 0.0, totalwithCheckedbaggage = 0.0;
char reply;
string input;
cin >> input;
string Yes = "YES";
string No = "NO";
string quit = "QUIT";
cout << "Enter your age. ";
cin >> age;
if (age > 18);
{
cout << "You are old enough to buy a ticket." << endl;
cout << "Would you like to purchase a ticket now? ";
cin >> reply;
if (input == Yes);
{
cout << "How many Adult Tickets? ";
cin >> adultTickets;
cout << "How many Senior Tickets? ";
cin >> seniorTickets;
cout << "How many Child Tickets? ";
cin >> childTickets;
cout << "How many Infant Tickets? ";
cin >> infantTickets;
cout << "Number of checked baggage? ";
cin >> baggage;
cout << endl;
if (baggage <= passengerTotal);
totalBaggagefee = passengerTotal*baggageFee1;
totalTicket = (adultTickets*adultFee)+(seniorTickets*seniorFee)+(childTickets*childFee)+(infantTickets*infantFee);
totalwithCheckedbaggage = totalTicket+totalBaggagefee;
{
cout << "Your total including check baggage is " << totalwithCheckedbaggage << "" << endl;
}
else (baggage >= passengerTotal);
totalBaggagefee = passengerTotal * baggageFee1 + 1 * baggageFee2;
totalTicket = (adultTickets*adultFee)+(seniorTickets*seniorFee)+(childTickets*childFee)+(infantTickets*infantFee);
totalwithCheckedbaggage = totalTicket+totalBaggagefee;
{
cout << "Your total including check baggage is " << totalwithCheckedbaggage << "" << endl;
}
else (input == No);
{
cout << "You are a minor, have an adult purchase your ticket. ";
cout << "Thank you." << endl;
}
cout << "Type quit to end. ";
cin >> reply;
cout << endl;
exit(1);
}
else if (age<18);
{
cout << "You are too young, have an adult buy your ticket. " << endl;
}
return 0;
}}
One problem I see is that you put semicolons ";" after the if, else and else if-statements. Remove them.
You can write an if-else-statement with or without curly braces. If you write it without brackets, only the first code part until the next semicolon gets executed if the if-statement evaluates to true. If you are using curly brackets, you can define a whole punch of statements within that curly brackets block. Code lines inside that block get executed when the expression inside the if-statement evaluates to true.
Take the following if-statement for example:
int age = 22;
if(age > 18) cout << "Hello World" << endl;
{
cout << "Inside block" << endl;
}
In this case "Inside block" gets printed everytime. Even if age is less or equals 18. The string "Hello World" only gets printed when age is greater then 18.
So if you put a semicolon after an if-else-statement, basically nothing happens because it's a perfectly valid statement that does nothing.
Let's take the first if-statement for example. Instead of:
if(age > 18);
{
you write:
if(age > 18) {
Whenever you are declaring a block with curly brackets, you normally don't need a semicolon before or after the block.
Your problems are with if and if-else syntax.
In C++ an if() condition controls the next statement and only the next statement.
Just to keep you on your toes 'next statement' can be empty.
So if(input == YES); means "if input is "YES", do nothing special and carry on".
An if followed by an empty statement isn't massively useful, but the syntax admits it.
If you want if() to control multiple statements then you introduce a block (which acts like a single statement in this respect).
Blocks are collections of statements surrounded by { and }
if (baggage <= passengerTotal);
totalBaggagefee = passengerTotal*baggageFee1;
totalTicket = (adultTickets*adultFee)+/*...*/;
totalwithCheckedbaggage =totalTicket+totalBaggagefee;
{
cout << "Your total including check baggage is " <<
totalwithCheckedbaggage << "" << endl;
}
else (baggage >= passengerTotal);
Should be:
if (baggage <= passengerTotal){//<---- Start block following condition!
totalBaggagefee = passengerTotal*baggageFee1;
totalTicket = (adultTickets*adultFee)+/*...*/;
totalwithCheckedbaggage =totalTicket+totalBaggagefee;
cout << "Your total including check baggage is " <<
totalwithCheckedbaggage << "" << endl;
} else if (baggage >= passengerTotal)
Notice I've replaced some code with /*...*/ to make it fit the screen nicely.
Also notice I've changed the else clause.
Before the else didn't match up with the if because the if finished several statements ago (due to the error with if() ;).
But the second problem was else (baggage>=passengerTotal); also does nothing.
In C++ you can just use an expression as a statement. That code will check the condition and ignore the result! Welcome to C++.
else isn't an implicit else-if so you have to explicitly make the else clause an if statement using else if.
There appear to be a number of similar errors but I'll leave it to you to tidy up fully.
On a style note, I recommend only using
if(){
}
or
if(){
} else {
}
And if you like
if(){
}else if (){
}
These can be composed into chains if necessary:
if(){
}else if (){
}else {
}
That is always follow if() with a statement block and ignore that if it's a single statement you don't need the { }. I tends to make things easier to read.
Why are things like if(flag==true); valid? Probably historical reasons inherited from the C syntax which was kept simple on the tiny machines it was designed on. if(flag==true); is the same as (flag==true); and unless there are side-effects (possible but very unwise) both do nothing.
If you ever do want to introduce an empty statement or block, I recommend a comment.
if(condition){
/* Does nothing.*/
}
That's not much use in an if-statement but you do see constructs like:
while(do_a_thing()){
/*Do nothing*/
}
If do_a_thing() returns false if there's nothing left to do.