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 2 years ago.
Improve this question
Here's my code:
std::cout << "The contaner is " << (!container)?"not":; "empty";
Which obviously doesn't work but I hope the idea is clear now. I want to print "The container is empty", and to add "not" before "empty" if bool container is false.
I'd like to know if it's possible or if I have to write something along the lines of:
if(container) std::cout ...;
else std::cout ...;
When all else fails, just use an if statement:
std::cout << "The contaner is ";
if (!container)
std::cout << "not ";
std::cout<< "empty";
Personally I like this better then using the conditional operator as it's easier for me to read. This also works when the types of the things you want to display are different. The conditional operator requires that both cases be converted to a common type so something like !container ? "not" : 1 wont work.
You're almost there. The ternary operator will need the else result, you can use an empty string "", then, due to precedence issues you will need to encapsulate the expression with parenthesis:
std::cout << "The contaner is " << (!container ? "not" : "") << "empty";
Try ... << (!container ? "not" : "") << "empty".
You can add the empty string in the non-empty case.
std::cout << "The container is " << (!empty ? "not ": "") << "empty";
Or turn down the cleverness level a bit, which I personally find more readable,
std::cout << "The container is " << (empty ? "empty": "not empty");
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 months ago.
Improve this question
I did not write this code.
i'm on my 3rd day of coding in C++ and i'm having a hard time understanding how incremnent works in general.
int main()
{
int antal_ord {};
double medellangd {};
string kort_ord;
string langt_ord;
int min_length {100};
int max_length {};
string S;
cout << "Mata in en text:\n" << endl;
while (cin >> S)
{
if (S.length() > max_length)
{
max_length = S.length();
langt_ord = S;
}
if (S.length() < min_length)
{
min_length = S.length();
kort_ord = S;
}
medellangd+=S.length();
antal_ord++;
}
if (antal_ord == 0)
{
cout << "Inga ord matades in." << endl;
}
else {
medellangd = (medellangd / antal_ord);
round(medellangd);
cout << "Texten innehöll " << antal_ord << " ord." << endl;
cout << "Det kortaste ordet var " << '"' << kort_ord << '"' << " med "
<< kort_ord.length() << " tecken." << endl;
cout << "Det längsta ordet var " << '"' << langt_ord << '"' << " med "
<< langt_ord.length() << " tecken." << endl;
cout << "Medelordlängden var "<< fixed << setprecision(1) << medellangd << " tecken.";
}
return 0;
}
antal_ord is the variable for the amount of words written in this scenario.
In the line where it says "cout << "Texten innehöll " << antal_ord << " ord." << endl;" how does it know how many words have been written? The only time this variable is used before this line is when the variable gets incremented, but how does that let the variable know how many words have been written in total?
and also the .length command, does it basically just count the amount of letters written?
There's really nothing special going on here. Every time you read one word with cin >> S, you increment antal_ord by one. Since you started with zero words written and antal_ord==0, at the end antal_ord will equal the number of words read from cin.
Similarly, S.length() returns the number of letters currently in S. In your case, that is exactly the number of letters read from cin since you didn't chance S after reading. But if you did S += " some extra letters, then S.length() will of course change.
When you'll learn about most programming languages, you'll start off with basics: syntax, data types, declarations (vars + funcs as well as other possible concepts), loops, calls, math operations and other code-control techniques relevant to each programming language.
What you'll see about most (and I;ll try to "rewind" from the generalization I started with and back down to C/C++) is that you have the following type of math operation variations when it comes to addition (let's focus on this, as it's more on point with the question).
result in a separate variable, in our case b: b = a + 1;
result in the same variable: a += 1;
incrementing the value of the variable: a++;
Expanding on it:
In the first case, b will have its value overwritten and is dependent on a different values (in this case the value of a and 1). What you need to focus on here is that a is NOT changed.
In this case, a receives a new value and is incremented by the right-side-value, in our case 1. a is changed by adding one (not incrementing)
In our case, similar to #2, the value of 8a* is updated, but the incrementation is done by 1.
Apart from syntactic sugar or code style preference, the difference between each is also in the way the variables are assigned their values (more formally said, in the assembly code "underneath"). This topic is a lot more complicated for someone that started programming, but focusing on the question, the answer is simply that ++ increments the value by 1.
Also note that there is a difference in certain coding flows between ++a and a++. Mainly in loops. For ++a the value is set before executing the code, using the already incremented value in the code, while a++ uses the current value of a first, then increments it.
Try it like this:
int i = 0;
while (++i < 100)
{
std::cout << i << std::endl;
}
... versus...
int i = 0;
while (i++ < 100)
{
std::cout << i << std::endl;
}
Then count how many lines each case wrote.
There is also a small caveat you should be aware of, it's a bit more advanced, so it's just a little "FYI" for you. There are two C++ techniques called "function overloading" and "operator (re)definition". Let's focus on the second one. You could build your own data type (for example a struct or class) and implement your own operators that do something other than what their arithmetic counterparts do. You'll see this in iterator definitions. In that case ++ is not "actual value incrementation" (so it's not a math calculation), but rather switching to the next item in a list. Once you reach std::vector lessons you'll encounter that.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
I have written a code that prompts the user to input a number and then tell them if it is odd or even. But it is giving me these errors that don't make sense at all.
How do you fix them?
Haven't used C++ in a while but i think it should look something like this
if(x%2 == 0)
{
std::cout << x << "is even\n";
}
else
{
std::cout << x << "is odd\n";
}
your errors are because you were basically saying
cout << x;
"is even";
which doesn't make sense to the compiler or to anyone what exactly is supposed to happen with "is even"
You should use cout << x << "is_even" instead of cout << x; "is_even";.
You get the warning about expression result unused because in your case you don't use "is even".
And the error is because after your if without {} brackets there are 2 expressions.
You can omit brackets and use else after if only if there is one expression after if.
Try adding {} around the code after if and you will get only warnings about expression result unused.
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 5 years ago.
Improve this question
I'm quite a newbie (started to learn about coding just like 2 weeks ago) and I'd really appreciate some help to explain why my code isn't working.
I wrote a simple code to calculate the probability. That's not really important part. The code requires some user input so in order to make it kinda foolproof, I wrote two if statements for various kind of wrong input (wrong data type, number too high, number too low) to throw an error message and kill the program. And if the input is right (means none of the conditions of the if statements is true), it should call a function diceTwo(des).
However, if I input number 8 - which should be allright - for some reason that I can't figure out - it triggers the number too high/low if statement, so no matter what number I enter, the function never gets called.
cin >> des;
if (cin.fail())
{
cin.clear();
cin.ignore(100, '\n');
cout << "Invalid input! Use only whole positive numbers!" << endl;
cout << "Try again." << endl;
return -1;
}
if (des> 12 || des< 1);
{
cout << "Invalid input!" << endl;
cout << "Remember the only possible values are from 2 to 12!" << endl;
cout << "Try again." << endl;
return -1;
}
diceTwo(des);
cout << "The probability of this roll is " << x << "%" << endl;
This is the part that makes troubles. I already tried to split the problematic if statement into two (one for <1, one for >12), or adding a new if statement for des>1 && des<12 to call the function, none of it worked. I worked with if statements to provide foolproofness for user input few times before, always worked well, so I really can't seem to find what's wrong this time. Anyone could tell me how to fix it please?
You have a semi colon after the if statement. Look CLOSELY:
if (des> 12 || des< 1); //<----- semi colon
{
cout << "Invalid input!" << endl;
cout << "Remember the only possible values are from 2 to 12!" << endl;
cout << "Try again." << endl;
return -1;
}
The semi colon terminates the if statement, so that your program just continues to the next line, which, happens to be your invalid input line. Remove the semi-colon and you're golden :)
Mistakenly added ; in if
if (des> 12 || des< 1);
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 7 years ago.
Improve this question
New to coding. The first part in the first link which is the character letter 'a' is correct. But then after that, its downhill from there.
Its showing me whats wrong, but I do not understand it.
You have declared several variables with the same name 'number' in the same scope. That is not allowed and leads to the error messages.
Within a scope (such as a function or loop or something), you can only declare a variable once. Otherwise, it would be ambiguous which one you were talking about.
The error is saying you've already declared a variable called number (as an int), and you cannot declare it again within the same scope.
Make the second variable called something else:
double dNumber = 1.11;
cout << "Please enter a double: " << dNumber << endl;
bool bNumber = 0;
cout << "Please enter a bool: " << bNumber << endl;
Note, it's usually more typical to set bool values to either true or false.
Now, if you really, really wanted to use the variable name number multiple times, you could put each section in curly braces:
{
double number = 1.11;
cout << "Please enter a double: " << number << endl;
}
{
bool number = 0;
cout << "Please enter a bool: " << number << endl;
}
In that case, you would no longer have access to that variable outside the curly braces, thus the reference is no longer ambiguous.
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 9 years ago.
Improve this question
As one can see, I am just starting out with C++ and just began my hello world program.
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!" << end1;
cout << "Hooray!" << end1;
system("PAUSE");
return 0;
}
But for some reason, unknown to me, I am getting an error on both of the cout lines, saying end1 was undeclared! How do I fix this?
end1
should be:
endl
You used a 1 (the number) instead of l (the letter).
that’s endL just like end LINE :P
It should be endl (end line), not end1 (end one?):
cout << "Hello, World!" << endl;
cout << "Hooray!" << endl;
endl represent end line, it is not end1.
You have a typo. Try endl instead of end1.
You should write endl instead of end1 (So make the one to a small "L")
It should be endl and not end1.
replace end1 by endl and it'll work just fine! :)
To avoid typos like the one you experienced,
instead of using "endl", you can use 'new line' by inserting '/n' inside the quote.
Example:
cout << " Hi, this is how you do it /n";
You only need to replace your
end1
with
endl
Thus you have a syntax error that you need to fix by replacing the one('1') with an 'l', thereby fixing your program. It should compile and run successfully now.