Error in Strings assignment. (C++) [closed] - c++

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've looked everywhere and I've found one for php but not c++. I'm making a little console rpg for a project in my into to c++ class and I'd like to avoid functions and/or if possible--but if not I'll use them.
Sample code:
int main(){
string pName;
string pWpnName;
int pDamage=0;
int wdSwrdD=1;
if (pDamage==wdSwrdD)pWpnName="Wooden Sword";
cout<<"Please enter a name";
cin>>pName;
pDamage++:
cout<<"Name: "<<pName<<endl;
cout<<"Weapon: "<<pWpnName<<endl;
return 0}
But whenever I do this it outputs: Name: pName (like it's supposed to) and Weapon:. It just stays blank and I have a feeling it's something to do with how I'm using strings...

You do not understand basics of how imperative languages (and C++ is one of them) work. Program executed statement by statement, and your if condition checks pDamage==wdSwrdD only once - when execution flow goes through that statement. So the fact that you increase pDamage later will not magically change pWpnName (and you need to change comparison operator == to assignment operator = in that if condition in addition to that, but I assume this is a typo).
So you most probably need a loop where execution flow is repeatedly goes through your if statement (that's what loops are created for), but it is difficult to say anything more based on information you provided.

You can use the getline() function:
cout<<"Please enter a name"<<endl;
getline(cin, pName);
pDamage++;
The function can get a line from a stream, set std::cin as the steam argument, and assign a line input to a variable.

Your problem is that you've made a typo: == is equality comparison, while = is assignment. So, your section of code should be changed:
if (pDamage==wdSwrdD)
pWpnName=="Wooden Sword"; // here you're doing comparison
...to:
if (pDamage==wdSwrdD)
pWpnName="Wooden Sword"; // here you're doing assignment
Most compilers should generate a warning for this behavior because it's an easy typo to make, but can be difficult to catch.

In your program you have not initialized the strings and your are taking user input for pName and therefore it displays the name . In case pWpnName it's not initialized while declaring and the "if condition never becomes true" because you have initialized pDamage=0 and wdSwrD=1 and as we know if(0==1) is never true the string pWpnName never gets initialized to Wooden Sword so it displays blank.

Related

Performance when using sequence of operations in a single line in cpp [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
Recently I have started looking into C++ from the basics and got to know (to my surprise) that I can give series of expressions in a single line separated by commas in some cases as below
//it'll execute all the expressions mentioned after condition seperated by comma
for(int i=0;condition;++i,++x,cout<<"in for loop"<<endl,z = z*2);
(x>y)? ++z,z1 = z*2, cout<<"printing statement"<<endl:cout<<"condition failed"<<endl,z = z/2;
Here, I have a confusion after this is working. Is it safe to code in that way or is there any problem coding in such a way?
Please clarify!!!
Correct me if i'm wrong anywhere, I'm just curious to know why most of the programmers don't use this way (I haven't seen such kind of lines anywhere)
The comma operator , evaluates each of its operands in sequence. In standardese, there is a sequence point between the evaluation of the left operand and the right operand.
In a expression which contains a comma operator, the value of the left operand is discarded and the expression takes on the value of the right operand. In both of the examples above, the comma operator is used in a void context, so none of the values are used.
So a statement like this where the value of the comma operator is not used:
exp1, exp2, exp3, exp4;
Is equivalent to the following sequence of statements:
exp1; exp2; exp3; exp4;
The first example is equivalent to the following:
for(int i=0;condition;) {
++i;
++x;
cout<<"in for loop"<<endl;
z = z*2;
}
And the second example:
if (x>y) {
++z;
z1 = z*2;
cout<<"printing statement"<<endl;
} else {
cout<<"condition failed"<<endl;
z = z/2;
}
Note that this is considerably more readable that the one-line versions. It's also easier to debug. Since debuggers typically step through code a line at a time, it breaks up the flow and is more granular.
Not indenting and spacing your code is not less costly regarding performance. It is unreadable, confusing and a pain to understand for you and for anyone who'd have to work with it.
Lot of people will prefer a well-syntaxed, beautifully and efficiently-indented code than a top-performance one. You can modify, debug and refract a code which might not work but has the advantage to be understandable.
On the other hand, very few codes remain unchanged and stay unread. There will always be a time when someone, may be you, will have to read it again and if it looks like the one if your OP, it will be very time costly to do.
It is allowed. In my opinion and i say without a reference that in general other programmers do not find your 'for' loop very readable. Sometimes in a for loop you want to do other things then just for (int i = 0; i < 10; ++i){"do something"}For example increment 'i' in every loop with two. Reading code should be like reading a text. If you are reading a book you do not want it to be unnecessary difficult.
Your other question was about the safety of the statement. The biggest problem with the code is that you might get confused about what you are doing exactly. Bugs are caused by human errors (computers are deterministic and are executing machine code which ultimately has been written by a human) and the question about safety mainly depends on how you define it.
To give you some tips. When i just started programming C++ i looked a lot on CPP reference. I will give you a link where you can read about the syntax and what is allowed/possible. On this website there are quite a lot of examples on all kinds of statements. They will in general not put 5 or 6 operations within in a single line. If there are more variables that you want to change then you might want to do that in the scope of the for loop so it will be more readable instead of inside the for loop.
http://en.cppreference.com/w/cpp/language/for

Endless do while loop in C++ code? [duplicate]

This question already has answers here:
Using the scanf() function
(4 answers)
Closed 5 years ago.
char input[256];
do{
cout<<"..."; //prompt
scanf("%s",&input5); //user inputs string
if(strcmp(input5,"block")==0)
{} //if the user types block, then it finishes the loop and goes to the cout at the bottom
else if(strcmp(input5,"attack")==0)
{
cout<<"..."<<endl;
}
else if(strcmp(input5,"look")==0)
{
cout<<"..."
}
else
{
cout<<"..."<<endl;
}
}while(strcmp(input5,"block")!=0); //loop ends when block is typed
cout<<"...";
I am having issues with my do while loop. I am doing a project for school that involves a text adventure kind of game. The user is prompting how to respond to an attack. The desired command is "block", which will move the user on to the next sequence. When "block" is typed into the scanf, it endlessly loops and prints what is in the "else" condition. I don't see what the problem is and all feedback is appreciated.
I just tried your code and it works fine (though I removed the & in the scanf), and created 'input5' as a char array.
Though that aside, there's a few things that you might want to change. I'd stick to using 'cin' instead of scanf, as you're mixing C and C++. That would allow you to use a 'string' for 'input5', and compare them using the '==' operator, which is quite a bit cleaner. Maybe think of a more descriptive name than 'input5' too, as if you've got lots of 'inputX' variables then things will get messy.
Edit: I'd also refrain from "using namespace std;", as you might end up with naming collisions.
Most likely you don't need the & operator before input5 on the scanf line, because the things scanf expects for %s fields are already pointers/arrays. Although I don't see how input5 is declared, so I'm not sure if this is the (only) problem. You should have included that in the code snippet also.
EDIT: Just a note: It's not particularly elegant to mix C-style (scanf) and C++ style (cout) IO. You wouldn't have this problem with cin.
Obviously, the loop does not terminate because the string comparison does not return equality. And this must be because input5 does not contain the typed input (and for the same reason, the else clause is executed whatever the input).
As input5 is only modified by the scanf call, this must be the root of the evil. A simple debugging session would have revealed it immediately.
The reason is simple: you must pass scanf the address of the buffer, but you are actually passing the address of the address, and overwriting the value of the variable input5 (for which we don't have the declaration but can infer char* or const char*).
In a 32 bits environment, this could cause a crash by overwriting the stack. Under 64 bits, you'll need more typing to obtain it.

If statement c++ with text [closed]

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 7 years ago.
Improve this question
My code:
{
int reply;
cout<<"Am I doing something wrong: ";
cin>> reply;
if-part( reply == "yes") {
cout<<"Good";
}
}
Hi guys, I am newbie, I googled and youtubed the stuff, but i just can not find an answer.
Why is this code not running well if you text in if condition, but if you put number, everything is fine?
Thank you.
In your case you are comparing an integer with a pointer (address)
if-part( reply == "yes") {
Reply is a in value.
"yes" is a c-string, so it is roughly equivalent to
const char *yes = "yes"
where yes would be a pointer to the first byte in the string in y_e_s -- for example, 0x75243
so you are comparing an integer value to a pointer value such as 0x75243 and they are unlikely to ever be equal.
In java script this would work (better) since it converts types for you -- C++ does not, at least not like this.
reply is of type int and you are comparing it as a string.That's not possible.
You can simply use:
if (reply == 1)
cout << "Good\n";

C++ Multi-Dimensional Array saving/loading to file error [closed]

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
I've been working on this C++ project for roughly 2 weeks now and I'm stumped on a couple things regarding 2D Arrays. To start off here is the code I wrote as of now:
http://pastebin.com/vCsz947Q
I decided to provide this as a pastebin link due to the fact that it's rather large (it uses 8 functions) and I thought it would save space in this post. I'm new to this site so I apologize if there's a better way that I'm not aware of.
The Problem:
When I go to save my "char seating" array to a .dat file using the "save seats" function that I created, I get a file that gives me the following garbage character " Ì " instead of the intended ' # ' (for open seats) or ' * ' (if a seat is bought).
My functions will save the intended amount of rows (15) and columns (30) despite this though. Also an asterisk will be placed when I go to "purchase a seat" in this program in the file. Additionally my program loads the files as intended, except for the fact that... Well... There's garbage data stored in the seat array.
I feel like this relates to another problem I'm having where if I go to the "purchase seats" function and I say to purchase a seat, it should replace a # with a *, but it doesn't, yet in the saved file it will show an asterisk in the intended spot... Which is very strange.
I have absolutely no idea why this occurs, and what's frustrating is this one thing that's preventing me from finishing this program. I want to believe that my original array in int main that's being called by other functions isn't being updated properly, but I don't know, which is why I came here to seek assistance.
Thank you for your assistance whoever can help.
Well for a start you have some undefined behaviour here inside your displaySeatingChart (char displaySeats[ ][30], float displayPrices[ ]) function with the following:
const int rowDisplay = 15;
const int colDisplay = 30;
as later within one of your loops you have
cout << displaySeats[rowDisplay][colDisplay];
which is clearly reading beyond the array bounds since in main() you define
const int rowMain = 15;
const int colMain = 30;
char seating[rowMain][colMain];
float seatPrices[15];
and pass both seating and seatPrices to the displaySeats function. There may well be other problems with your code but this at least is a clear example of undefined behaviour. Consider stepping through the code with a debugger to get a clearer idea of the source of the issue.
On another note given that you are working with C++ consider working with std::vector instead of arrays. This will give you more scope to ascertain the dimensions of the items that arrays that you are working with from within your utility functions and result in less potential for errors in array access.

Which one is preferred when checking arguments? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
For example, I have a method which accepts some arguments like
method1(int i)
the argument int should be either 1 or 2
I can use assert (i == 1 || i ==2)
or throw exception if (!(i==1) || (i==2)) throw std::exception
which one is better. I am always confused about assert vs explicit throw.
It really depends on the situation.
There are four major groups of error handling:
assert - used to deal with programming errors ("We don't expect this function to get a NULL pointer, and if it does, it's because some other part of our code is broken, and it should NEVER happen"). If the assert wasn't there, the code would probably crash, loop forever, or otherwise "fail".
exceptions - such as std::invalid_argument - this is more used when the program EXPECTS things to go wrong, and there is some way to "try again". More likely when the actual user is using the program wrong - e.g. inputs from keyboard/file, etc. As the name states, this should be an "exception" - something unusual and unexpected.
return value - when an error is entirely likely (trying to see if the serial port is on port COM1, COM2, COM3 or COM4 or "is the result of the equation matching what I expect yet?")
Let it crash - if the inputs are wrong, the application runs out of memory, etc, just crash. It may seem like a rough method, but sometimes there's not much better you can do anyway - what are you going to ACTUALLY do in the middle of your compiler if some linked list is broken and the next node is not pointing at your special sentry pointer, but to NULL? Printing a message may be a little better, but not a huge amount.
Is the integer passed to method1 always going to be done so by a programmer, or might it be passed in by the users of your application?
Assert,
for example if your code looks like this:
int i;
if ( condition ) {
i = 1;
}
else {
i = 3;
}
method1(i);
If this is the case, you'd likely want to use an assert, because it indicates you (the programmer) has made an error. If i = 3, you want your program to blow up and make it obvious there is a problem in your code, so you can catch it before you release it to your clients.
Throw an exception,
on the other hand, if your code looks like this:
int i;
cin >> i;
method1(i);
You're passing the user's input to the function. You can't anticipate what they might enter. So if it's an invalid value, you should throw an exception or return an error code and handle it accordingly (e.g., print out a message to the user saying they have entered an invalid number).
Generally asserts are checked in debug builds but not release builds. If you want to save time and skip the check in your final released code, then asserts are the way to go. If your function needs to blow up in the face of unexpected input even in release, then the exception may be the way to go.
Of course the details of exactly what you should do for error conditions will vary with context beyond what was provided in your example.