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

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.

Related

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.

Issue Comparing strings for an Answer Key (C++)

I'm working on a midterm project for my coding class, and while I've gotten the majority of kinks worked out I'm struggling with comparing two string values and determining if they are equal or not. The strings in question are ANSWERKEYand studentAnswers. The former is a constant that the latter is compared to.
The code in question is as follows.
if (studentAnswers == ANSWERKEY)
{
percentScore = 100.0;
cout << "Score: " << percentScore << " % " << 'A' << endl;
}
else if (studentAnswers != ANSWERKEY)
{
int count = 0;
double answerCount = 0.0;
while (count < ANSWERKEY.length())
{
if (studentAnswers.substr(count, count+1) == ANSWERKEY.substr(count, count+1)
{
answerCount++;
count++;
}
else
{
cout << "Incorrect answer." << endl;
count++;
}
}
percentScore = ((answerCount) / (double)ANSWERKEY.length()) * 100.0;
cout << "Percent score is " << percentScore << "%" << endl;
}
The exact issue I'm facing is that I can't work out a better way to compare the strings. With the current method, the output is the following:
The intro to the code runs fine. Only when I get to checking the answers against the key, in this case "abcdefabcdefabcdefab", do I run into issues. Regardless of what characters are changed, the program marks roughly half of all characters as mismatching and drops the score down because of it.
I've thought of using a pair of arrays, but then I can't find a solution to setting up the array when some values of it are empty. If the student's answers are too short, e.g. only 15 characters long, I don't know how to compare the blank space, or even store it in the array.
Thank you for any help you can give.
First:
if (studentAnswers == ANSWERKEY)
{...}
else if (studentAnswers != ANSWERKEY)
{ ...}
looks like an overkill when comparing strings. And where is the else part ?
Second, this is risky. Read the IEE754 and articles about cancellation, or even SO:
double answerCount = 0.0;
...
answerCount++
Third:
You are checking character by character using substr. To me it feels like using a hammer to kill a bacteria.
studentAnswers.substr(count, count+1) == ANSWERKEY.substr(count, count+1)
Fourth:
What if studentAnswers is shorter than ANSWERKEY ?
Conclusion:
You need to clarify inputs/expected outputs and use the debugger to better understand what is happening during execution. Carefully check all your variables at each step fo your program.

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.

Why is my nested loop producing the same output?

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?

Need help cleaning up fibonacci sequence using C++ please

I'm still very new to C++ still and decided to make a fibonacci sequence. It worked (Woo!) but it doesn't work as well as I would like it to.
what I mean by that is say for example I told my program to count the first 10 terms of the sequence I will get
"0, 1, 1" and then I have to press enter for each additional number until it hits ten in which case the program returns 0 and ends.
How do I get the program to display all the numbers I want to without hitting enter for each additional one?
Here is my script:
#include <iostream>
using namespace std;
int main()
{
int FibNum;
cout << "How many numbers of the Fibonacci Sequence would you like to see? \n\n";
cin>> FibNum;
cin.ignore();
int a = 0;
int b = 1;
int c = 2;
cout << "Fibonacci Sequence up to " << FibNum << " terms.\n\n";
cout << a << "\n" << b << "\n";
for (int c = 2; c < FibNum; c++) {
int d = a + b;
cout << d;
cin.ignore();
a = b;
b = d;
}
}
Thanks in advance for any help!
P.s. Also if you notice anything terrible I'm doing please feel free to correct me, I'm very aware I'm probably doing a lot wrong, I'm just trying to learn. :]
A few things:
1) Remove int c = 2; as you're re-defining c inside the for loop.
2) Drop the line cin.ignore();: in your for loop: that will fix your "enter" problem; that line waits for some input then ignores it.
3) Put some white space in your output: e.g. cout << d << ' ' so your numbers are separated.
4) [Acknowledge vincent_zhang] Consider moving to uint64_t as your data type for a, b, and d. This is a standard type in C++11. It's a 64 bit unsigned integer type; adequate for a large number of terms.
and a small thing, bordering on personal opinion,
5) Use ++c instead of c++ as the former will never run slower as, conceptually at least, post-increment has to take a copy of the original value.
Besides the previous answers,
To better format the output, add white space by changing this
cout << d;
to
cout << d << " ";
You may want to change the type of a, b and d from int to double to prevent overflow.
(If you let FibNum=100 in your code, you should be able to observe overflow, meaning that you are going to get some incorrect numbers toward the end of the sequence.)
Move cin.ignore() out of the loop then you dont need to enter to print all the 10 numbers of Fibonacci series