So I'm making a program that asks a user if they want to do something. The answer is as simple as Y/N. I would like the program to be able to accept both capital and lowercase "Y". Problem is, when I type while (answer == 'Y', answer == 'y') only the lowercase "Y" is accepted. If I type while (answer == 'y', answer == 'Y')
What am I doing wrong?
(More info: "answer" is the name of my "char" variable, and I'm using the "iostream", "cstdlib", and "string" libraries)
You need to use the 'logical or' operator ||
So your code would become while (answer =='Y' || answer == 'y')
You should be using the logical operator for or ("||"):
while( answer=='Y' || answer=='y' ){
//code
}
Also, FFR:
http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B
The problem is that you're using the comma operator instead of an "or" operator, like the logical or, ||.
From Wikipedia:
In the C and C++ programming languages, the comma operator
(represented by the token ,) is a binary operator that evaluates its
first operand and discards the result, and then evaluates the second
operand and returns this value (and type). The comma operator has
the lowest precedence of any C operator, and acts as a sequence point.
(emphasis added)
Its the comma operator's property to return the second operand only (it executes both operands though). Consider the following code:
int main() {
int i=1, j=2, k=3;
int l= (i,cout<<"print; ",j,k);
cout << l;
}
Because of the comma operator, output is 'print; 3'.
So try avoiding this comma operator in your code, and as stated above by many, use instead a logical (||) operator.
Related
Why does following code doesn't compile?
for(int i = 0; i < 10; i++){
if(i == 5) i = 7, continue;
}
Comma can be used as a separator as well as operator. And if it acts like operator, it evaluates both the expressions and returns the last. I understand that it is not acting as operator here since continue is not an operand. But why is it not acting as separator of two statements.
It shows the following error-
error: expected primary-expression before ‘continue’
if(i == 5) i = 7, continue;
The comma token can act as a separator. But those contexts are explicitly enumerated. It's a separator for declarations, function/template parameters, function call/template instantiation arguments, and in initializers like {1, 2}. It is not a separator for statements, that's the role of a semi-colon.
The comma operator separates expressions. And a continue statement is not an expression.
Don't be a "clever" coder. Write clear code, understandable at a glance. Put the assignment in its own statement and wrap the two statements in one block scope for the if to execute.
This question already has answers here:
comma separated expression in while loop in C
(5 answers)
How does the Comma Operator work
(9 answers)
Closed 5 years ago.
string command;
string bookName;
while (cin >> command, command != "END")
{...}
Here in while loop's condition, there is a comma.
I know that multiple conditions can be added using && or ||.
But why use ,?
Is there any certain benefits? Can you please explain the usage and syntax?
It's the comma operator, also known as the "evaluate and forget" operator. The effect of a, b is:
Evaluate a, including any side effects
Discard its value (i.e. do nothing with it)
Evaluate b
Use the result of b as the result of the entire expression a, b
The author of the loop wanted to express the following:
Read command from cin, and then enter the loop body unless command is equal to "END"
However, they would have been better off using && instead of , here, because cin >> command can fail (i.e. if the end of input is reached before the word END is found). In such case, the condition with , will not do what was intended (it will likely loop forever, as command will never receive the value END), while the condition with && would do the right thing (terminate).
I have a vector of strings and I want to compare the first element of the vector with a bunch of different "strings".
Here is what i wanted to do:
if (strcmp(myString[0], 'a') == 0)
but strcmp doesnt work. I basically want to check the contents of myString[0] with a bunch of different characters to see if there is a match. So it would be something like
if (strcmp(myString[0], 'a') == 0){
}
else if (strcmp(myString[0], 'ah') == 0){
}
else ifif (strcmp(myString[0], 'xyz') == 0)
etc..
What can i use to do this comparison? Compiler complains about "no suitable conversion from std:string to "constant char*" exists so i know it doesnt like that im doing a string to char comparison, but i cant figure out how to correctly do this.
std::string overloads operator== to do a string comparison, so the equivalent to
if (strcmp(cString, "other string") == 0)
is
if (cppString == "other string")
So your code becomes (for example)
else if (myString[0] == "ah")
'a' is not a string, it is a character constant. You need to use "a", "ah", "xyz", etc.
Also, if you want to use strcmp, you need to use:
if (strcmp(myString[0].c_str(), "a") == 0)
You can also use the overloaded operator== to compare a std::string with a char const*.
if (myString[0] == "a")
You have marked this post as C++.
compare the first element of the vector with a bunch of different
"strings".
If I am reading your post correctly, the first element of the vector is a std::string.
std::string has a function and an operator to use for string-to-string comparison.
The function is used like:
if (0 == pfnA.compare(pfnB))
As described in cppreference.com:
The return value from std::string.compare(std::string) is
negative value if *this appears before the character sequence specified by the arguments, in lexicographical order
positive value if *this appears after the character sequence specified by the arguments, in lexicographical order
zero if both character sequences compare equivalent
The operator==() as already described, returns true when the two strings are the same.
I am currently learning C++ from 'Problem solving with C++' (9th, W. Savitch). The book shows an example of a while loop. The while loop looks as follows.
while (ans = = 'Y' || ans = = 'y')
{
//compound statement
}
ans is of type char.
The boolean expression appears to be trying to use the equality operator, and in the context of the //compound statement this makes sense. However, I always thought whitespace was illegal within the equality operator. i.e == is legal, but = = is illegal.
When I copy the code and compile it, my compiler throws the error 'expected expression' when it hits = = as if I am trying to assign an expression to a variable. I am almost certain this is a typo within the book. However, just in case the book is trying to throw a curveball I thought I would ask...
Many thanks!
Is whitespace between the two ='s in an equality operator legal in C++?
No. = = is two = tokens. == is one == token. You can't use the former when you mean the latter.
This question already has answers here:
How does the Comma Operator work
(9 answers)
Closed 9 months ago.
I came across unexpected (to me at least) C++ behavior today, shown by the following snippit:
#include <iostream>
int main()
{
std::cout << ("1", "2") << std::endl;
return 0;
}
Output:
2
This works with any number of strings between the parentheses. Tested on the visual studio 2010 compiler as well as on codepad.
I'm wondering why this compiles in the first place, what is the use of this 'feature'?
Ahh, this is the comma operator. When you use a comma and two (or more) expressions, what happens is that all expressions are executed, and the result as a whole is the result of the last expression. That is why you get "2" as a result of this. See here for a bigger explanation.
It's called the comma operator: in an expression x, y, the compiler
first evaluates x (including all side effects), then y; the results
of the expression are the results of y.
In the expression you cite, it has absolutely no use; the first string
is simply ignored. If the first expression has side effects, however,
it could be useful. (Mostly for obfuscation, in my opinion, and it's
best avoided.)
Note too that this only works when the comma is an operator. If it can
be anything else (e.g. punctuation separating the arguments of a
function), it is. So:
f( 1, 2 ); // Call f with two arguments, 1 and 2
f( (1, 2) ); // Call f with one argument, 2
(See. I told you it was good for obfuscation.)
Comma operator ( , )
The comma operator (,) is used to separate two or more expressions that are included where only one expression is expected. When the set of expressions has to be evaluated for a value, only the rightmost expression is considered.
For example, the following code:
a = (b=3, b+2);
Ref:http://www.cplusplus.com/doc/tutorial/operators/
The result of the comma (",") is the right subexpression.
I use it in loops over stl containers:
for( list<int>::iterator = mylist.begin(), it_end = mylist.end(); it != it_end; ++it )
...
The comma operator evaluates the expressions on both sides of the comma, but returns the result of the second.