Why is my nested loop producing the same output? - c++

I am writing a program to find a 4-digit address. The program should continually allow the user to enter digits until the correct answer is solved. Additional parameters are:
All four digits are different
The digit in the thousands place is three times the digit in the tens
place
The number is odd
The sum of the digits is 27
With the program I've written so far it gives me the same output of "address is correct" no matter the input is. Trying to figure out what I am doing wrong, but no success. This is the code I've written so far.
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int main()
{
int const Address = 9837;
int input;
char Y;
char N;
int sum;
int even;
int i;
cout << "Please enter a 4-digit number." << endl;
cin >> input;
{
while (input = Y || N)
{
if (input = Y)
cout << "Please enter a 4-digit number" << endl;
else if (input = N)
cout << "Good Bye!!" << endl;
return 0;
}
while (input != Address && Y && N)
{
if (sum = input == !27);
cout << "Not a valid address - the sum of the digits is not 27" << endl;
if (input % 2 == 0)
cout << "Not a valid address - the number is even." << endl;
}
input = Address;
cout << "Address is correct." << endl;
}
}

You include <cmath> and <string> but you don't use anything from that headers.
Declare/define variables as close to where they're used/needed.
You are using the variables N and Y uninitialized. They contain an indeterminate value (=garbage). If char happens to be unsigned, reading an indeterminate value (an uninitialized (unsigned) char) under a few certain conditions is allowed. But you use N and Y in a way where reading their values causes undefined behaviour.
The variables even and i are never used.
With cin >> input; you try to extract an integer from standard input. If the user would enter Y or N or anything else that is not an integer, extraction would fail. You need two different ways to get the users input: 1 to let the user enter his guessed number and 1 to let the user choose if he wants to play again.
You introduce a block ({) after cin >> input; that serves no purpose.
while (input = Y || N) ... Comparison is done with the operator == in C++ (and C) but = is assignment. The expression input = Y || N assigns the result of Y || N to input but since Y and N are uninitialized and chances that both contain the value 0 is quite low (0 || 0 would evaluate to false), input will almost always be 1 (true converted to an int is 1) and the loop will always execute.
Actually, reading the values of Y and N causes undefined behaviour because they're uninitialized. Theoretically (since the compiler knows that Y and N have indeterminate value), it can generate any code it likes.
Within the first while-loop:
if (input = Y) // is again an assignment, not a test for equality
cout << "Please enter a 4-digit number" << endl;
else if (input = N) // again
cout << "Good Bye!!" << endl;
return 0; // will always exit the program, no matter the value of input
In case all hell breaks loose and N and Y are both 0 by chance and thus the 2nd while-loop is reached, it is sure, that input is 0 (because otherwise the controlled statement of the 1st while-loop would have been executed and exited the program by return 0;). When input equals 0 it isn't equal to Address so input != Address yields true but since we know that N and Y are 0 (false) and true && false gives false, the controlled statement of the 2nd while-loop doesn't get executed.
I'll skip the contents of the controlled statement of the 2nd while-loop. Sufficive to say, they don't do what you think they do.
input = Address; // that assignment serves no purpose
cout << "Address is correct." << endl;
is the output you always get when the variables Y and N are 0, which might happen (especially when running debug-code).
Please, stay away from the source you're currently learning C++ from. Get a good textbook and start over.

Is the piece of code you have captured here missing something or incomplete? I see that Y, N and sum are not assigned any value and thus all conditions checks fail... Eventually it will display "Address is correct" always...

Remember that = and == are totally different.
= means an assignment. eg: int x = 100; means put the value of 100 into the variable x.
== means comparison or (is equal to). eg: if (x == 100), means if x has the value 100.
Also, If you're trying to make a choice variable for Yes or No,
You should do it this way:
char ans;
if (ans == 'Y' || ans == 'N")
Since your input variable is an int, and your choice variable is a char, your while statement is not valid.

A few things you need to know:
You should assign values to things before calling them
You should read about the difference between = and ==
If you want multiple inputs, your cin >> input; should be in your while loop
Your code is not well indented at some places
You are declaring a i integer, but you are never using it.
In other words: your compiler must be giving you a LOT of warnings. Did you look at them?

Related

My c++ code isn't letting me input a variable

I am very new to c++ and I was trying to put together a script that just says how much older/younger someone is than me. The problem is the std::cin isn't working, it's not letting me say the input age. How do I make this work?
#include <iostream>
int main()
{
int age;
int diff = age - 20;
std::cout << "What is your age?\n";
std::cin >> age;
/* There should be an option to say the age, but it goes right into the next code with a random number */
if (diff < 20) {
std::cout << "You are " << diff << " years younger than me.\n";
}
else if (diff > 20) {
std::cout << "You are " << diff << " years older than me.\n";
}
else if (diff = 20) {
std::cout << "You are my age.\n";
}
}
When you say int age;, there's no rhyme or reason to the bits stored in memory that represent that integer. It's undefined behavior, but it will be equal to some random value based on what bits happen to be there. You then use std::cin to store an integer there, which works fine (assuming your code keeps chugging along despite using age before it has a value). Your conditionals then compare diff, which has a random value minus 20, with 20, outputting the right statement based on whatever was stored in diff. For example, when I ran your code, I got the output, "You are -1635346580 years younger than me." To fix this problem, read the value of the user's age before using it like this:
int age;
std::cout << "What is your age?\n";
std::cin >> age;
int diff = age - 20;
Additionally, when you wrote else if (diff = 20), you used an assignment operator. That puts the value of 20 into the variable diff. It then returns that value for use in the expected Boolean. In C++, 0 translates to false, and everything else translates to true. That means, once it gets there, it will always execute since 20 becomes true. Your program will always function correctly, however, since by that point in the code, diff is guaranteed to be 20 since it's neither greater than 20 nor less than 20. You could say else if (diff == 20) to do the comparison, but I'd replace it with else // diff is 20 since you know the value by that point.

If statement is always false in c++

I'm working my way thought Bjarne Stroustrup Programming Principles and Practice (4.64 Drill #6) and for some reason I can't get "if" to be true.
I've initialized my variables to -1000.
I can't initialize to null.
I've tried just declaring them
I've tried changing the order of my variables.
The problems I've found on stack overflow my code is much different than theirs.
I've currently added a vector which I wasn't using prior.
double val1 = 0; // initialized
double smaller; // initialized
double larger = 0; // initialized
vector<double> compare; // empty vector of doubles
int main ()
{
cout << "Please input a value, us | to stop\n"; // put into
while (cin >> val1) // cin "get from"
{
compare.push_back(val1);
if (val1 < smaller)
{
smaller = val1; // assignment giving a variable a new value
cout << val1 << " is the smallest so far \n" ;
compare.push_back(smaller);
}
else if (val1 > larger)
{
larger = val1; // assignment giving a variable a new value
cout << val1 << " is the largest so far \n";
compare.push_back(larger);
}
else
{
cout << val1 << " error\n";
}
}
}
I can't get smaller "is the smallest so far to print.
I'm teaching myself so any input would be greatly appreciated if anything in my code isn't correct or the best practices please let me know.
Thank You in Advance,
The first value enter must be both the larger and the smaller whatever that value, for that you need to initialize smaller with INFINITY (all valid values are smaller) and larger with -INFINITY (all valid values are larger) and to remove the else to have the two clauses effective for the first value, the third clause has no sense and must be removed.
Is it also useless to use global variables, I encourage you to not use global variables the more you can.
Because the same value can be enter several time perhaps you want a set rather than a vector to not save several times the same value ? However you do not use compare after ...
You write the message Please input... only one time, in that case it is more consistent to say Please input values... or replace
cout << "Please input a value, us | to stop\n"; // put into
while (cin >> val1) // cin "get from"
{
by
while (cout << "Please input a value, invalid value or EOF to stop" << endl,
cin >> val) // cin "get from"
Your code can be changed to be :
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
int main ()
{
double val;
double smaller = INFINITY; // initialized
double larger = -INFINITY; // initialized
vector<double> compare; // empty vector of doubles
cout << "Please input values, give an invalid value or EOF to stop" << endl; // put into
while (cin >> val) // cin "get from"
{
compare.push_back(val);
if (val < smaller)
{
smaller = val; // assignment giving a variable a new value
cout << val << " is the smallest so far" << endl;
compare.push_back(smaller);
}
if (val > larger)
{
larger = val; // assignment giving a variable a new value
cout << val << " is the largest so far" << endl;
compare.push_back(larger);
}
}
// do something with compare ?
return 0;
}
Execution :
pi#raspberrypi:/tmp $ ./a.out
Please input values, give an invalid value or EOF to stop
1234
1234 is the smallest so far
1234 is the largest so far
1
1 is the smallest so far
222
222222
222222 is the largest so far
-123
-123 is the smallest so far
23
45
aze
pi#raspberrypi:/tmp $
Initialise your variables to INFINITY.
double smaller = INFINITY;
double larger = -INFINITY;
The first value will be smaller/larger than any of those, so you don't limit their value range.
edit: As somebody in the comments pointed out, you would also have to remove the else between the smaller/larger parts, as for that first round, both would apply. As for the third case, not sure what that is meant to do.

C++ Loop - Finding smallest and second smallest value

I'm very very new to C++. Here I'm trying to write a program without any extra library. Using loops to find both the smallest value and the second smallest value from the user's inputs ( 0 is excluded and exits the program ).
Here is what I tried to do.
#include <iostream>
using namespace std;
int main()
{
int value=0;
int SmallestNumber=0;
int SmallestNumber2=0;
cout << "Enter number to find the smallest and second smallest(or 0 to exit): ";
cin >> value;
while (value != 0) {
if (value< SmallestNumber && value != 0 )
{
SmallestNumber = value;
}
else if (value<SmallestNumber && SmallestNumber2 >SmallestNumber && value != 0)
{
SmallestNumber2 = value;
}
cout << "Enter number to find the smallest and second smallest(or 0 to quit): ";
cin >> value;
}
cout << "Smallest number is: " << SmallestNumber << '\n' << endl;
cout << "Second Smallest number is: " << SmallestNumber2 << '\n' << endl;
return 0;
}
However, this program is not functioning properly. The smallest number finder works only if I input a negative value **, and the second smallest number value always outputs **0.
Since I'm very new to C++, I tried many other solutions, but this is what I can really think of.
Can somebody please tell me what is wrong with the program, and how I can correct it?
A million thanks! Please help me :'(
Thanks for answering my question!
I changed the initialization into this.
int value;
int SmallestNumber=0;
int SmallestNumber2=0;
but how do I initialize the smallest and the second smallest values..?
This is what I wanted my program to do
displaying the smallest and second smallest
50
1
61
93
-35
38
0
-35 smallest
1 second smallest
You start with a smallest value set to 0, so you will always get values only smaller than 0, that's why you have std::numeric_limits<int>::max().
Then for your second smallest, you are never checking against the current second smallest value, you are just checking against the biggest, which you now is going to work. So change this:
if (value>SmallestNumber2 && value != 0)
You should probably check value != 0 outside the main if statements as well. And as #Caleb reminded me, what happens to the previous largest value if it gets replaced?
Also, if you want to keep the same concept and do the algorithm "yourself" there is few things to change.
First the initial value of SmallestNumber and SmallestNumber2 need to be as high as possible otherwise the numbers saved can only be the one lower than your initial value. Therefore you can use INT_MAX.
Second, the second smallest number, need to be set in 2 cases :
when a new value is entered that is the second smallest
when a new smallest value is set, the old smallest value become the new second smallest.
Third there are a lot of unnecessary code here. You check too many time if value is not null which you know from the while condition. And you have code duplication with the cout/cin statement. Which is prone to mistakes.
Here is a version of what it could look like :
int value= INT_MAX;
int SmallestNumber=INT_MAX;
int SmallestNumber2=INT_MAX;
while (value != 0) {
if(value > SmallestNumber && value < SmallestNumber2)
{
SmallestNumber2 = value;
}
else if (value< SmallestNumber)
{
SmallestNumber2 = SmallestNumber;
SmallestNumber = value;
}
cout << "Enter number to find the smallest and second smallest(or 0 to quit): ";
cin >> value;
}
cout << "Smallest number is: " << SmallestNumber << '\n' << endl;
cout << "Second Smallest number is: " << SmallestNumber2 << '\n' << endl;
return 0;
ps : the version of #darune is a nicer solution.
You have no position at which the former smallest value becomes the second smallest value, which can't work.
Consider this code:
int value;
int smallest = std::numeric_limits<int>::max()-1;
int second_smallest = std::numeric_limits<int>::max();
while(true)
{
cin >> value;
if(value == 0) break;
if(value >= second_smallest) continue;
if(value == smallest) continue; // assuming that a double value does not change anything
if(value > smallest) // is between them
{
second_smallest = value;
continue;
}
//now the case left is that the new value is the smallest
second_smallest = smallest;
smallest = value;
}
Basic idea: first of all, rule out things and from then on, assume that they do not hold. We begin with the break case (I prefer a while(true) in such cases to have manual control over breaking it inside). Then we rule out the case in which nothing happens. The two cases left are that we are between the old values and that we are below both, and we handle them accordingly.
In your code, your ifs get to bloated. Makes it hard to keep track of what is done and what is to be done.
One example of this is that you have several times && value != 0 in your code despite this always being true due to the condition of your while.
In general, you should really learn how to use a debugger, or at least how to use helpful messages for debugging. Your mistake of setting your variables to zero at the start would have been easy to detect.
Other minor things: You should decide for a style and stick to it. It is quite unusual to name variables with a major first letter. Camel case is fine though, smallestNumber would have been fine. Second, try to avoid using namespace std;. This can lead to collissions. Rather use single members of std, like using std::cout;. It is not that problematic in a source file (very problematic in a header) but I recommend to do it consistently to keep a good routine.
A thing left to do in the code would be to later catch if the variables are still at std::numeric_limits<int>::max() and that minus one, signalling that there was no user input, and printing a fitting message instead of those values.
Note that as you read in an integer, negative values are legal, which might not be what you want, given that you use zero to break. You might want to add a case
if(value < 0)
{
cout << "Value was ignored due to being negative" << endl;
}
This is relatively simpel by using a a few different concepts, namely stdvector, stdstream and last stdsort
First off, the input part can be simplified to:
std::vector<int> numbers;
std::cout << "Enter multiple numbers, separated by spaces: ";
std::getline(std::cin, line);
std::istringstream stream(line);
while (stream >> number) {
numbers.push_back(number);
}
Now, since you would like the 2 smallest numbers, my suggested method would be to simply sort the vector at this point:
std::sort(numbers.begin(), numbers.end());
Now the list of numbers are sorted in ascending order and it is matter of printing the 2 first values. I leave that as an exercise to you.

Check if input is not integer or number at all cpp

I've created a guessing game where you have to guess randomly generated number in range from 1 to 100. I also managed to restrict a user if they enter a number that is out of the range, and requires new input. The problem is when you accidentally enter letters or symbols. Then it enters an infinite loop. I tried:
while(x<1 || x>100 || cin.fail())//1. tried to test if input failed (AFAIU it checks if input is expected type and if it is not it fails)
while(x<1 || x>100 || x>='a' && x<='z' || x>='A' && <='Z') // 2. tried to test for letters at least
while(x<1 || x>100 x!=(int)x)//3. to test if it is not integer
{ cout<<"Out of range";
cin>>x;
}
For one solution, you could try and use isdigit. This checks to see if input is actually a number. So you can do something like:
if(!(isdigit(x))){
cout << "That is not an acceptable entry. \n";
continue;
}
EDIT: I should say, that after researching this, I realized that for isdigit to work, the entry needs to be a char. However, this can still work if you convert the char into an int after it discovers that it's an int. Example:
if(!(isdigit(x))){
cout << "That is not an acceptable entry. \n";
continue;
}
else{
int y = x - '0';
}
That int y = x - '0' might seem odd; but it's there because you have to convert the char to an int, and according to the ASCII coding, to do so, you subtract the character '0' from the desired number. You can see that here: Convert char to int in C and C++

How to make C++ program that is supposed to add up ages and separate it into categories?

I'm supposed to make a program that counts the number of people in each age group:
0-16 (including 16) is infant
16-29 is young
29-55 is middle
55-75 is old
75+ is really old
The intervals are closed to the left and open to the right.
I wrote a program that compiles, but does not give me the correct values. I'm new at coding so can anyone point me in the right direction? Here is what I have:
#include <iostream>
using namespace std;
main()
{
int countinfant, countyoung, countmiddle, countold, countreallyold;
char age;
countinfant=0;
countyoung=0;
countmiddle=0;
countold=0;
countreallyold=0;
cout<< "Please Enter Ages. To end, enter *\n";
cin.get(age);
while (age>0 && age != '*')
{
if (age>=0 && age<=16) countinfant = countinfant + 1;
if (age>16 && age<=29) countyoung = countyoung + 1;
if (age>29 && age<=55) countmiddle = countmiddle + 1;
if (age>55 && age<=75) countold = countold + 1;
if (age>75 && age>=76) countreallyold = countreallyold + 1;
cin.get(age);
}
cout<< "\n The Number of Infant's Are: " << countinfant;
cout<< "\n The Number of Young's Are: " << countyoung;
cout<< "\n The Number of Middle's Are: " <<countmiddle;
cout<< "\n The Number of old's Are: " <<countold;
cout<< "\n The Number of Really Old's Are: " <<countreallyold;
cout<<endl;
return 0;
}
Actually your problem is very easy to figure out once I looked closer at the code.
The get function of input streams read a single character and not numbers. So if you enter the character 5 as input it will be read and stored in age as a character, and if the encoding used on your system is ASCII encoding (which is the most common these days) then the value for the character '5' is the integer 53.
You then proceed to use the character you have read as an integer, which as it is encoded will give you the wrong results.
To get the correct values you need to read an integer, however since you want to check for the asterisk to end the input you can't use normal integer input with the >> operator, which is why you used get I guess. The solution is to use strings and check the string for the asterisk, and if not an asterisk convert the string to an integer.
Something like
std::string input;
while (std::cin >> input && input != "*")
{
int age = std::stoi(input);
...
}
It does not work because you declared age as a char. The program reads the input as a char, so if you enter 0, the value in age will be the ASCII code of the character 0, which is 48 (0x30). You need to declare it as int age; and for the exit condition simply enter a negative value, e.g. -1, don't use the '*'.