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 6 years ago.
Improve this question
I am very new to C++. My objective is to write the following logic:
if a = yes then print "ok", else return 0
Here is my code so far:
int a;
cin>>a;
if (a = "Yes") { // Error right here
cout<< "ok"; << endl;
}else{
return 0;
}
First of all, what do you want your program to do?
You need to distinguish assignment and equal to operator.
Please note that you need to understand the basics before proceeding to perform conditional statements.
A reasonable program should go like this:
int a;
cin>>a;
if (a == 5) { // 5 is an integer
cout<< "You entered 5!" << endl; // no semicolon after "
}
return 0; // must be out of the else statement
= assigns things.
Use == to compare, however you are comparing an int with a string.
If you are not careful, you compare the address of a char * with a number when dealing with strings.
Use a std::string instead.
#include <string>
//.... some context I presume
std::string a;
cin >> a;
if (a == "Yes") { // Error right here
cout<< "ok"; << endl;
}else{
return 0;
}
There are multiple errors in this code.
You need to use the comparison operator in your condition. This is denoted by the double equal sign "==". Your code is using assignment "=" which tries to assign the value "Yes" to the variable a. This is a common error in C/C++ so you need to be careful whenever you compare things.
The other error is that you have declared the variable a to be an integer, so you will get a type mismatch error when you try to compile because "Yes" is a string.
Your code is incorrect in terms of data types. You have a variable 'a' of type int which you are comparing to string "yes". Try to see it from a logical point of view; you can compare:
2 numbers (for example, 2 is greater than 1)
2 strings (for example, "food" is not the same word as "cat")
Etc...
In your case, you are comparing a number inputted(let's assume 5) to a word "yes". When you try to input a letter for var a, you will get a compilation error. Therefore, simply change the following:
string a;
Another problem with your code is when the if-then loop checks the condition; a comparison operator is 2 equal signs next to each other instead of a single equal sign. A single equal sign assigns the item on the right to the item on the left. For example, in:
int num = 5;
The variable num is assigned 5. But you want to make a comparison, not assign the variable its own condition!
Your loop is always true because you set the variable to the condition it is supposed to meet. You also need to do the following:
if (a == "yes")
This compares the value stored in var a to the value on the right side of the == .
Just some advice, I would recommend you to get some good books on c++. Search them online. You can also take online programming courses on edx, course record, etc... . There are a lot of other free learning resources online too which you can make use of. You may also want to dive into a simpler programming language; I would recommend scratch. It gives you a very basic idea about programming and can be done in less than a week.
** Note that I feel this is the simplest way; however, you can also set type of a to a char, accept input and then convert it back to a string. Good luck!
Related
I am currently reading "A tour of C++" from Bjarne Stroustup, and I saw the following example:
bool accept()
{
cout << "Do you want to proceed (y or n)?\n"; // write question
char answer = 0; // initialize to a value that will not appear on input
cin >> answer; // read answer
if (answer == 'y')
return true;
return false;
}
I thought using multiple return statements wasn't recommended. Wouldn't it be better practice in this case to create a bool variable, initialize it to 0 and then modify it in the if condition, to finally return the value of this boolean variable? Or I am just making things up.
No, you're not entirely making things up, and no there is no recommendation of such that I know of.
Snippet According to your recommendation:
Int accept()
{
Int result=0;
cout << "Do you want to proceed (y or n)?\n"; // write question
char answer = 0; // initialize to a value that will not appear on input
cin >> answer; // read answer
if (answer != 'y')
result=1;
return result;
}
Looking closer you will notice no difference between the snippet above and the one you found in the book, they book use validation, the difference is the data-type used.
Now, it will be more easy to use a boolean if you need to simple use the function accept like below:
if(accept()) /*do something*/;
Rather than:
if(accept()==0) /*do something*/
Either way, you're good to go.
Another thing to consider is the size of your data-type, boolean is just 1bit while int is 4bytes so comparison time complexity will obviously be different but you will most likely never notice the difference.
Edit:
In java boolean is 1bit as said above but since it's c++, because of the issue of 1bit not addressable, it only make more sense to make it 8bit and then it can be given an address in the memory.
So, in C++ boolean is also 1byte or 8bit, and so the comparison time difference is not a thing to consider.
Both approaches are possible, but you will usually see the version using multiple return values. Take a look how this part of the code works:
if (answer == 'y')
return true;
return false;
At first you may see two branches in which the executed code can go, based on the value of answer. First one is connected with y choice, and the other one with anything else. This code could also look like this:
if (answer == 'y')
return true;
else
return false;
But it makes the program a bit more complicated - there is one more jmp instruction in assembly code, which means that the code is just a bit more complex, but its functionality is exactly the same as of the previous version.
Now, we can add the bool variable and let's see how it will look like:
bool is_answer_positive = false;
if (answer == 'y')
is_answer_positive = true;
else // we can get rid of this statement
is_answer_positive = false; // as we have defined variable earlier
return is_answer_positive;
The first thing which makes the code a bit more complex is a new variable, which does not add any vital value to the code, I would say it makes it only more complicated. This is the first instruction which makes the code bigger, but not better. Then if/else works similarly to the second version, but you also assign some values to the is_answer_positive, which also makes the code bigger, but not better. At the end, you return the value you got from if/else statement and the code is done. We can get rid of else statement, as is_answer_positive was initialized to be false, but this is still not the best solution.
Comparing those three possibilities: first version is the most used one, it is clear and probably the simplest, second version adds extra jump, which is unnecessary at all, and the third version adds extra variable, which makes the code a bit harder to read.
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 3 years ago.
Improve this question
newbie here messing around and i encountered this error: expected primary-expression before '||' token. checked ever post I could find with similar issues but with no luck.
any help greatly appreciated!
#include <iostream>
#include <string>
using namespace std;
int main()
{
string txt;
while(txt == "") || (txt == " ");
{
cout << "Please enter the sentence you want to translate.";
cin >> txt;
}
}
The syntax for while is (roughly):
while(condition)
block
where block is either a single statement or multiple statements enclosed in { and }.
There is no semicolon after the condition and the condition needs to be wrapped in parentheses.
I recommend you to learn C++ from a good introductory book. Your instructional material should explain to you the syntax of grammar constructs and you should not try to guess it.
The reason you are getting this error message from the compiler is because it is seeing the || operator and expecting to find two "primary expressions", one on each side of the ||. In your case, while(txt == "") is not a primary expression.
from https://learn.microsoft.com/en-us/cpp/cpp/primary-expressions?view=vs-2019, a primary expression is:
100 // literal
'c' // literal
this // in a member function, a pointer to the class instance
::func // a global function
::operator + // a global operator function
::A::B // a global qualified name
( i + 1 ) // a parenthesized expression
It can be confusing because the compiler looks at your code differently than you do and can have a hard time understanding what you are attempting to write even when it seems obvious to you.
What you were trying to do, write a while loop, is spelled like this in C++
while(condition)
statement
//or
while(condition)
{
statements...
}
The condition can be a compound expression like the one you used
while((txt == "") || (txt == " "))
{
cout << "Please enter the sentence you want to translate.";
cin >> txt;
}
Try surrounding the entire while condition with parentheses:
while ((txt == "") || (txt == " ")) {
...
}
I have a question regarding a school lab assignment and I was hoping someone could clarify this a little for me. I'm not looking for an answer, just an approach. I've been unable to fully understand the books explanations.
Question: In a program, write a function that accepts three arguments: an array, the size of the array, and a number n.
Assume that the array contains integers. The function should display
all of the numbers in the array that are greater than the number n .
This is what I have right now:
/*
Programmer: Reilly Parker
Program Name: Lab14_LargerThanN.cpp
Date: 10/28/2016
Description: Displays values of a static array that are greater than a user inputted value.
Version: 1.0
*/
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
void arrayFunction(int[], int, int); // Prototype for arrayFunction. int[] = array, int = size, int = n
int main()
{
int n; // Initialize user inputted value "n"
cout << "Enter Value:" << endl;
cin >> n;
const int size = 20; // Constant array size of 20 integers.
int arrayNumbers[size] = {5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24}; // 20 assigned values for the array
arrayFunction(arrayNumbers, size, n); // Call function
return 0;
}
/* Description of code below:
The For statement scans each variable, if the array values are greater than the
variable "n" inputted by the user the output is only those values greater than "n."
*/
void arrayFunction(int arrayN[], int arrayS, int number) // Function Definiton
{
for (int i=0; i<arrayS; i++)
{
if (arrayN[i] > number)
{
cout << arrayN[i] << " ";
cout << endl;
}
}
}
For my whole answer I assume that this:
Question: In a program, write a function that accepts three arguments: an array, the size of the array, and a number n. Assume that the array contains integers. The function should display all of the numbers in the array that are greater than the number n .
is the whole assignment.
void arrayFunction(int[], int, int); is probably the only thing you could write. Note however that int[] is in fact int*.
As others pointed out don't bother with receiving input. Use something along this line: int numbers[] = {2,4,8,5,7,45,8,26,5,94,6,5,8};. It will create static array for you;
You have parameter int n but you never use it.
You are trying to send variable to the function arrayFunction but I can't see definition of this variable!
Use something called rubber duck debugging (google for it :) ). It will really help you.
If you have some more precise question, ask them.
As a side note: there are better ways of sending an array to the function, but your assignment forces you to use this old and not-so-good solution.
Would you use an if else statement? I've edited my original post with the updated code.
You have updated question, then I update my answer.
First and foremost of all: do indent your code properly!!!
If you do that, your code will be much cleaner, much more readable, and it will be much easier understandable not only for us, but primairly for you.
Next thing: do not omit braces even if they are not required in some context. Even experienced programmers only rarely omit them, so as a beginner you should never do so (as for example with your for loop).
Regarding if-else statement the short answer is: it depends.
Sometimes I would use if (note: in your case else is useless). But other times I would use ternary operator: condition ? value_if_true : value_if_false; or even a lambda expression.
In this case you should probably settle for an if, as it will be easier and more intuitive for you.
Aside from the C++ aspect, think about the steps you need to do to figure out if a number is greater than a certain value. Then do that for all the numbers in the array, and print out the number if it's greater than n. Since you have a 'for' loop, it looks like you already know how to do a loop and compare numbers in C++.
Also, it looks like in your arrayFunction you are trying to input values? You can't input a whole array's worth of values in a single statement like you appear to be trying (also, 'values' is not the name of any variable in arrayFunction, so that would not be recognized when you try to compile it).
This question already has answers here:
Why can't the switch statement be applied to strings?
(22 answers)
Closed 6 years ago.
Ok, so I got an error when I tried to print something based on the user's input. Pretty standard stuff, right? So, if the program would have worked correctly, the user would have entered six words or phrases that would be stored in the string named PhrasesAndWords. Then, each part of the array would have been tested, by creating a while-loop, using the counter as the index in the switch statement. Well, apparently, this didn't work, because it wasn't a constant expression, or a constexpr. The variable can't be a constant expression, though, since that would result in an infinite loop. By the way, here is the error:
C:\Users\henry\Desktop\NotTheActualPathForThisProject\main.cpp|34|error: switch quantity not an integer|
Aaand here's the code I wrote (I have gotten rid of irrelevant variables and such, though):
int main() {
string phrasesAndWords[6];
cin >> phrasesAndWords[0] >> phrasesAndWords[1] >> phrasesAndWords[2] >> phrasesAndWords[3] >> phrasesAndWords[4] >> phrasesAndWords[5]; // Recieve input
int counter = 0;
while (counter < 6) {
switch(phrasesAndWords[counter]) {
case "RandomString":
print("That sure was quite random. \n")
default:
print("I don't understaahnd... \n")
};
counter++;
};
};
Switch in C++ doesn`t work with strings. Cosider mapping the expected cases with integers.
The expression used in a switch statement must have an integral or enumerated type, or be of a class type in which the class has a single conversion function to an integral or enumerated type.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
How could I explain how and when to use an if-statement vs. a switch statement in a "Choose Your Own Adventure" game?
The game is basically structured that if you put in a certain answer, it changes the flow or direction of the game. I've usually used if-statements with functions, but is that the most efficient and simple way to teach?
Thanks!
Edit: Wow, thank you SO much for so many great answers!! Just one last note: if you were a 13-year-old trying to grasp this concept without any previous knowledge of programming, how would you try to go about to understand it? Seriously, thanks so much for the help!!
There are (give or take) five different solutions to "I've received this input, what do I do now".
If/else if/else ... chain. Advantage is that you can use any expression that can be made into true or false. Disadvantage is that it can get pretty messy when you have a long chain of them.
Switch - great for "there are lots of almost similar things to do". Drawback is that the case labels have to be integer values (or char values, but not strings, floating point values, etc).
A table which makes the long if/else into a much simpler if(table[index].something) ...
Function pointers - sort of a table pointer variant - store a pointer to the function that does whatever you want to do if you move in that direction.
Objects using virtual functions. Again, a variant on the table solution, but instead of storing function pointers, we store objects with some member function that we can use to "do whatever you need to do".
The correct solution in this case is perhaps a combination/variation on one of the latter 3 - in my opinion, at least.
In this very scenario you've described an if statement is pretty much your best option since the code needs to compare an answer provided by the user with some pre-defined options.
Those options will most likely be strings. switch statements in C++ cannot work on strings. Thus a series of if statements will probably be simpler.
A switch statement can be used when the answer only consists of a number or a single character.
For example, the code piece for the game's main menu could look like this:
Console output:
Please select an action:
1) Start a new game.
2) Go to options screen.
3) Quit game.
code:
int userChoice = getUserInput();
switch(userChoice){
case START_NEW_GAME: //1
startGame(); break;
case OPTIONS: //2
showOptions(); break;
case QUIT: //3
exit(); break;
}
Use a switch statement when you're identifying cases of numeric or ordinal values.
switch (number)
{
case 1: DoSomething();
break;
case 2: DoSomethingElse();
break;
}
Use if, elseif and else for more complex conditions, like numeric ranges.
if (number > 0 && number <= 100)
{
DoSomething();
}
else if (number > 100 && number <= 1000)
{
DoSomethingElse()
}
else
{
NotifyOutOfRange();
}
switch statements are for speed. That's why they are only numeric. The compiler will attempt to make a lookup table for non-sparse (i.e. contiguous) value ranges which can improve performance significantly when the code is constantly being executed. This is because it only needs to do 1 comparison for a contiguous range to determine what piece of code to execute.
switch statements potentially can cause hard to find bugs since at the end of each case you need to specify a break or the execution will fall through to the next case.
if/else if/else statements are for more general use. They are in general, slower than an equivalent switch statement if there are many comparisons against the same value. However if that if chain of statements is not executed a lot and the chain is not that long, the performance improvement is negligible.
For more general usage, if is the way to go. In a CYOAG, you will not be needing speed. The slowest part of the game is the user.
To explain this to a 13 year old:
If you think that you will be executing a comparison on a single
integer (whole number) value over 1,000,000 or more times all at once and you need
it to be done as quickly as possible, use a switch statement.
Otherwise, doesn't matter. Just be careful when using a switch, because if you
don't have a break at the end of each case you will be scratching you head
trying to figure out what just happend? when two or more cases are executed.
You can use switch statements if you have too many "else if" statements :)
More seriously, if a player has many different choices (like picking from 26 different options (a-z), then switch is the way to go).
Well, you can't really put strings into switch/case. That leaves you with if. or you'll need to implement parser that reads strings, maps them to some enum type, and then uses said enum within switch/case.
However a better (more extensible) way would be to use map of function callbacks.
Something like this:
#include <map>
#include <string>
#include <iostream>
typedef void(*ActionCallback)();
typedef std::map<std::string, ActionCallback> ActionMap;
static bool running = true;
void leftAction(){
std::cout << "\"left\" entered" << std::endl;
}
void rightAction(){
std::cout << "\"right\" entered" << std::endl;
}
void quitAction(){
std::cout << "game terminated" << std::endl;
running = false;
}
int main(int argc, char** argv){
ActionMap actionMap;
actionMap["left"] = leftAction;
actionMap["right"] = leftAction;
actionMap["quit"] = quitAction;
while(running){
std::string command;
std::cout << "enter command. Enter \"quit\" to close" << std::endl;
std::cin >> command;
ActionMap::iterator found = actionMap.find(command);
if (found == actionMap.end())
std::cout << "unknown command " << command << std::endl;
else
(*found->second)();
}
return 0;
}
The big advantage of this approach is that you can change commands at runtime. Add new commands, remove them, etc. You could even go a bit further and add lisp/python/lua binding and make it even more extensible.