C++ array greater than 0 print code - c++

I am having issues with this block of code:
else if (mineOrRefine == "refine" || mineOrRefine == "Refine")
if (StoneInventory[0] == 0)
cout << "You currently have no stone!" << endl;
int a = StoneInventory[0];
else if (a == >1)

You're not saying what the problem is, but I can all but guarantee it has to do with a lack of braces. Put your if and else blocks into braces, even when it's just one line, to reduce confusion. I'm not going to get into a debate about whether to put braces around a single expression following if/else in general, only that, in your case, the lack of braces is confusing you, so put them in.

instead of ( a== >1), use (a>=1) or (a>0)
also, any 'if' statement with more than one line of code should use curly braces. ie: if (x) { /* code */ }.

You're lost in the ifs, and you really need to add curly braces to see what's going on. The code amounts to this:
if (something_you_havent_shown)
{
// something else you haven't shown
}
else if (mineOrRefine == "refine" || mineOrRefine == "Refine)
{
if (StoneInventory[0] == 0)
{
std::cout << "You currently have no stone!" << std::endl;
}
}
int a = StoneInventory[0];
else if (something_you_say_youve_changed_since_asking_the_question)
The else in that last line doesn't go with any preceding if -- they've all finished, because each one applies only to the next line.

Related

Conditional if statement bug

For an assignment in my C++ programming class, we're supposed to create a program that will ask for order information for a product to be shipped, such as price, if it's fragile, the designated country, etc. Everything else except for one little if statement doesnt work correctly, and it's the one that prints out an error message if when typing in the country, it's not one of the three listed, no matter what I type, it always spits out the error!
if(shippingDestination!="AUS" || shippingDestination != "CAN" || shippingDestination != "USA")
{
cout<<"\nWrong destination ! Exiting........."<<endl;
system("pause");
exit(0);
}
(And yes, prior to this statement, the input by the user is forced into uppercase, and I have tested this without the statement above, everything works as intended)
I've tried several different variations to this conditional statement to try and get a favorable result, but no matter what I do, it always, always spits out the error.
There is a problem with your logical operators.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string shippingDestination="";
cout<< " Enter Destination ";
cin>>shippingDestination;
if(shippingDestination!="AUS" && shippingDestination!="CAN" && shippingDestination!="USA" ){
cout<< "Wrong Destination";
}else{
cout<< "Correct Destination";
}
}
Don't use "||"! What you want is: &&.
if (shippingDestination != "USA" && shippingDestination != "CAN" && shippingDestination != "AUS") {
cerr << "Wrong desitnation. << endl;
return 1; // It's convention to return 1 when there is an error.
}
if you use the or operator || in the if statement then if any of those conditions are true then whatever is inside the if condition is executed. What you need is the and operator && for this operator all the conditions have to be true. Also I found this answer pretty interesting
How an 'if (A && B)' statement is evaluated?

Optimized code for two string compare in if condition

I want to do two string compare and used two different if condition. Is there any better way to do string compare in one if condition
if (strcmp(Buff1(), Config1) == 0)
{
if (strcmp(Buff2, Config2) == 0)
{
// my code goes here
}
}
The equivalent code is:
if ((strcmp(Buff1(), Config1) == 0)) &&
(strcmp(Buff2, Config2) == 0))
{
// my code goes here
}
Note: The compiler should generate the same machine code for both code samples. The difference is cosmetic and primarily aimed at the reader of the code.
You do get a difference when you add else clauses:
if (strcmp(Buff1(), Config1) == 0)
{
if (strcmp(Buff2, Config2) == 0)
{
// my code goes here
}
else
{
// else 1
}
}
else
{
// else 2
}
Compared to:
if ((strcmp(Buff1(), Config1) == 0)) &&
(strcmp(Buff2, Config2) == 0))
{
// my code goes here
}
else
{
// Single else clause
}
In addition to Klas's answer(just in case you're not familiar with the AND operator) - the AND operator ('&&') checks the first condition and it continues to check the second condition -only if- the first condition is true.
So in your specific question, it checks if the first couple of strings are equal and only if true (are equal), it checks if the second couple are also equal.
The obvious optimization (not mentioned yet), if you know anything about those strings, is to first perform the compare that is more likely to fail.

How to have if, else nested tree continue working through the remaining else if’s…

I have a mini program I’m working on for class. The program is of correct syntax. Logically I cannot get the program to compute the remaining data after it completes the first else if statement that it matches.
I am subtracting numbers from each (a >= b) at each else if, the remaining value I am then assigning to a variable temp and using (temp >= c), rinse and repeat till value is zero. Each else if, will assign a char ‘A’ – ‘Z’ depending on the scenario. The problem I am having is it will meet one of the first else if’s but will not continue working the remaining else-ifs. I know this is standard of how if, else works. My question is how would I go about getting the remaining else ifs examined after the first one checks out. Is the only solution to use a switch function? Is there no way I can use if else and have each else checked/passed till my value = 0?
Just forget using else if, use a chain of if statements instead. For example:
bool isThisThree(int number, string &message)
{
if(number == 1)
message = "No, it's a one!";
if(number == 2)
message = "No, it's a two!";
if(number == 3) {
message = "Yes!";
return true;
}
if(number == 4)
message = "No, it's a four!";
if(number == 5)
message = "No, it's a five!";
return false;
}
In this example, the if statements will be examined one by one until the function hits a return statement.

C++ const char if-statement

So I'm trying to get this program that will say good or bad depending on your answer and I didn't want to have a really long if and else if statement with a bunch of strings so I put a bunch of possible answers in two chars and I want it to answer depending on what you say. The program only replies to the good answers saying good even if you enter in one of the bad answers.
const char* good[5] = {
"good", "great", "amazing", "amazing!", "fantastic"
};
const char* bad[5] = {
"bad", "bad pal", "bad eugene", "not good", "not good pal"
};
string input01 = "";
int main() {
cout << "Hello" << endl;
system("PAUSE");
system("CLS");
cout << "How are you doing today?" << endl;
cin >> input01;
transform(input01.begin(), input01.end(), input01.begin(), ::tolower);
if (input01 == good[0 > 5] || good[0 < 5]){
system("CLS");
cout << "good" << endl;
system("pause");
}
else if (input01 == bad[0 > 5] || bad[0 < 5]){
system("CLS");
cout << "bad" << endl;
system("pause");
}
}
This: if (input01 == good[0 > 5] || good[0 < 5]) probably doesn't do what you expect (because I can't imagine wanting what it really does).
0 > 5 is evaluated as a test of whether 0 is greater than 5. Since it's obviously not, that produces false. Since it's being used in a context where an integer is needed, that's converted to 0, so that part of the expression becomes if (input01 == good[0].
Likewise, 0 < 5 tests whether 0 is less than 5 (which it obviously is) so the result is true, which converts to 1, so that part of the expression is good[1]. Since that in turn is being used as a Boolean expression, it's treated as equivalent to good[1] != 0.
So what you have overall is if (input01 == good[0] || good[1] != 0).
That seems close enough to useless that I'm pretty sure it's not what you wanted. In particular, good[1] is a pointer. A pointer will compare equal to 0 if and only if it's a null pointer. Since it's initialized to point at something, it's not a null pointer, so that part of the expression will always evaluated as true.
of course, your other if statement is about equally useless.
If you want to check whether input01 is equal to any of the items in good, you might (for one example) use std::find:
if (std::find(std::begin(good), std::end(good), input01) == std::end(good))
// input01 was not present in `good`.
To make that work correctly, you'll want to use std::strings though:
std::vector<std::string> good{"good", "great", "amazing", "amazing!", "fantastic"};
It's kind of pointless for only 5 items, but if you lists of good and bad words are likely to get really large, you'd probably be better off sorting them, then using std::binary_search, or else using std::unordered_set instead.
Try:
if ((strcmp(input.c_str(), good[0]) == 0) ||
(strcmp(input.c_str(), good[1]) == 0) ||
...
(strcmp(input.c_str(), good[4]) == 0))
Or better switch the keywords to strings,
const string good[5] = {
"good", "great", "amazing", "amazing!", "fantastic"
};
and then
if ((input == good[0]) ||
(input == good[1]) ||
...
(input == good[4]))
Or even better, pack the keywords into a set
const set<string> good{"good", "great", "amazing", "amazing!", "fantastic"};
and then
if (good.find(input) != good.end())
Why don't you just check if the input01 is in your array. You should be able to use the find() function to do this. Something like
if(std::find(std::begin(good), std::end(good), input01) != std::end(good))){do something}
You may not need the std:: references

Unable to reduce the code (combine cout with exit)

I'm allowed to insert only 10 lines (strict) of codes into my program. I have optimized to program to a concise one. I have posted the code below.
if (std::find(outvar.begin(), outvar.end(), line[x].tokens[0]) == outvar.end() || (std::find(inputs.begin(), inputs.end(), line[x].tokens[4]) == inputs.end())
{
cerr << "Undefined variable " << endl;
exit(1);
}
if (opr[x].type == "MUL" && opr[x1].asap_value == my_cycle + 1)
{
opr[x1].asap_value = my_cycle + 2;
update_slack();
update_matrix(opr[x1].opid, 0);
}
if (latency < (opr[p2].asap_value + opr[p2].latency_op - 1) || opr[p2].asap_value == 0)
{
cerr << "Latency value is too less for this circuit \n"; return -1;
}
This alone takes 10 lines and I have 2 more compulsory lines of codes that has to be added. I'n unable to further reduce it. Basically I'm looking to combine the err(cout) statement along with the exit (return) statement into a single statement.
Any help will be greatly appreciated.
Thank you
You could make this all into one line using commas:
opr[x1].asap_value = my_cycle + 2, update_slack(), update_matrix(opr[x1].opid, 0);
Not sure if this is considered cheating. You haven't specified what the rules are exactly.
You need to understand that there is no obvious relationship between the number of statements and the code efficiency. That is because, for example the statement cout<<x; is not a single instructions for your processor. There can be hundreds or even thousands of instructions that the processor must execute in order to achieve the goal of that statement. Also, there are some statements, like a = b + c; that are translated into 2-3 instructions.
So, by reducing the number of statements, you don't optimize the code. There are other ways of optimization, like using a more efficient algorithm.