C++ variable value not changing - c++

I'm using the following code (it's been super simplified to get to the root of my problem).
#include <iostream>
namespace std;
int user;
int submit(int);
int main() {
user = 1;
submit(user);
user = 2;
submit(user);
return(0);
}
int submit(int user) {
if (user = 1) {
printf("1");
} else if (user = 2) {
printf("2");
}
return(0);
}
I thought that this would print out "12" but instead I'm getting "11". Isn't the variable "user" getting redefined before the function is called for the second time?
What's going wrong here?

Use ==, not = to check the values of user. You're overwriting the values (with =) instead of comparing them (with ==).

You are using = not == in your function body.
if (user = 1) { //This assigns user the value of 1 and then prints 1
printf("1");
The correct test condition should be :
if (user == 1) { //This checks the value of user and then prints if the condition is true
printf("1");
While compiling, if using gcc, adding the option -Wall is helpful in such cases as it gives you a warning about assignments in test conditions.

As answered by the experts, You are using = instead of using == in your function body that's why you are getting wrong output.
Here, I would like to clear your concept why it happens:
I hope you know the difference between assignment operator and equality operator. If not, I'm going to describe it briefly.
Assignment operator (=):
The assignment operator assigns a value to a variable. e.g.
user = 1;
This statement assigns the integer value 1 to the variable user.
This statement will always be executed which indicates that it is logically TRUE statement (assuming variable user is declared already).
As there is no comparison or something like that, so if we use Assignment operator(=) as a condition, it will always return TRUE or 1
Equality operator(==):
The equality operator is used to compare two values to know if they are equal or not.
user == 1;
This statement will compare the value of variable user with 1 and it will return TRUE if the value of user is 1 otherwise it will return FALSE.
RESULT: Assignment operator will always return TRUE but comparison operator may return TRUE or FALSE.
Now coming back to your code:
int submit(int user) {
//as you're using assignmnt operator this if condition will always true regardless of input
if (user = 1) {
printf("1");
//because if condition is true, it will never go into else if condition
} else if (user = 2) {
printf("2");
}
return(0);
}
So, actually, whenever you call this function, it will print 1 each time regardless of the value of user passed to this function. Since, you have called this function 2 times. Therefore, it will print 11.

Related

How do I use flag variables to produce output for a program designed to search an array for a string provided via user input?

I'm working on an ungraded practice assignment and am struggling with the C++ code required. The assignment parameters are to write a program which takes a string provided by user input, searches an array containing 10 elements, and sets the value of a flag variable depending on whether or not user input matches a string contained within the array. The program then outputs a phrase if the string was not found, as determined by referencing the value of the flag variable.
I have the following code so far:
// MichiganCities.cpp - This program prints a message for invalid cities in Michigan.
// Input: Interactive
// Output: Error message or nothing
#include <iostream>
#include <string>
using namespace std;
int main()
{
// Declare variables
string inCity; // name of city to look up in array
const int NUM_CITIES = 10;
// Initialized array of cities
string citiesInMichigan[] = {"Acme", "Albion", "Detroit", "Watervliet", "Coloma", "Saginaw", "Richland", "Glenn", "Midland", "Brooklyn"};
bool foundIt = false; // Flag variable
int x; // Loop control variable
// Get user input
cout << "Enter name of city: ";
cin >> inCity;
// Write your loop here
for(x=0; x<NUM_CITIES; x++){
// Write your test statement here to see if there is
// a match. Set the flag to true if city is found.
if(citiesInMichigan[x] == inCity)[
set foundIt = true,;
break;
]
}
// Test to see if city was not found to determine if
// "Not a city in Michigan" message should be printed.
if(foundIt == false){
cout << "City not in Michigan.";
return 0;
}
} // End of main()
I'm fairly certain what I've got here should do what I'm trying to do, but I get syntax errors requesting brackets [] in odd places and I'm lost on what I'm doing wrong.
I'm not looking for someone to provide correct code for me to simply copy, as I'm trying to learn. I'm looking for someone who can explain what I've done wrong, what rules I'm breaking, and/or what steps I can take to get this code working.
You have the right idea, but have a couple of syntactic mistakes.
First, blocks in C++ (and many other languages), are denoted by curly braces ({ and }), not square brackets like you have in your condition.
Second, setting a value to a variable is done by the assignment operator, = (i.e., somevariable = somevalue). There is no "set" keyword in C++.
To put those two points together, the condition inside the loop should look like this:
if (citiesInMichigan[x] == inCity) {
foundIt = true;
break;
}

Return 0 in if statement, does it means true/false or the program runs successfully?

First, if return 0 statements are removed, my program cannot run exactly. So I don't understand what does this means.
Secondly, one more problem is that it doesn't print the string "Accept 1-4 key only." at the end. If I press others key(not 1-4), the program stop and exit.
When I change if- else if statement to switch. It can run.
I am not able to figure what is going wrong in the program?
char key;
key = getchar();
fflush(stdin);//fpurge(stdin);
//1. play game
if (key == '1') {
if (Money >= 0.25) {
Money = Money - 0.25 + PlayGame();
}else {
printf("\nYou dont have enough money to play\n");
SaveGame (Money, "d:/SaveGame.txt");
return 0;
}
//2. Save game
}else if (key == '2') {
SaveGame (Money, "d:/SaveGame.txt");
//3. Cash out
}else if (key == '3') {
printf("Thank you for playing, you end with %.2f", Money);
remove("d:/SaveGame.txt");
return 0;
//4. Quit
}else if (key = '4') {
remove("d:/SaveGame.txt");
return 0;
//5. Wrong key
}else {
printf("Accept 1-4 key only.");
}
}while(1);
return 0;
}
return 0 is a programming convention that is used during program exit to indicate that the program have executed without errors. On the other hand, a > 0 return code indicates an error is encountered.
On your question, if return 0 is removed, program cannot run. It just means that the function that you are using is expecting an integer to be returned like below.
int main() {
....
}
If you are willing, you can also consider using switch/case statements instead of if/else. Note also that there is a logic error on your last else if. Should be key == '4'.
Assuming you have used int main() to run the code. int main() is a function in c/c++ with return type int, hence, you are supposed to use a return statement to run the code without errors.
Now, return 0 is a programming convention which indicates that program has executed without errors.
else if (key = '4') indicates assignment operator, not comparison operator which is ==.
If this code is inside the main function, there are three portable return values: 0, EXIT_SUCCESS, and EXIT_FAILURE. The latter two are constants that are defined in the header <cstdlib>. Returning 0 is equivalent to returning EXIT_SUCCESS. The values of those two constants are determined by the target system, that is, they will be values that the OS treats as success and failure, respectively.
In short: return 0; tells the system that the program succeeded. So does return EXIT_SUCCESS;. return EXIT_FAILURE; tells the system that the program failed.
There's one quirk here, though: in C++ (but not in C) you can leave out the final return statement from main:
int main() {
}
when execution reaches the end of main, it acts as if there was a return 0; just before the closing }. Personally, I've never liked that; I always write return 0; at the end of main. Your mileage may vary.

Why my or operator doesn't work?

Why can't I get the right string. What do I have wrong in the expression? I can't figure it out. I've stocked for hours.
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string>
using namespace std;
int main (){
string var = "y";
string constant ="y";
if ((var != constant )||( var != "n")){
cout << "error";
}
else {
cout << "right" // this is what it should print
}
}
I understand that or operator uses || as symbol. So why can't my program perform its task
Your program's results are correct.
Since var is set to "y", then the expression
var != "n"
is obviously true.
As such, the full expression
if ( .... || var != "n")
evaluates to true. By definition "anything OR true" is always true.
No matter how much you want your else statement to execute, it will not. Because it should not be.
There is nothing wrong with your program(aside from the syntax error at line 14). Your testing if var and constant are not equal, or var does not equal 'n'. The or statement works fine, because you're basically saying: if (condition or true), which will always be true because if he or operator finds only one condition true it will return true.
I believe what you want is the and, &&, operator. It only returns true if both of its conditions are true.
That being said above, even with the && operator your still going to have to change your code. Your error\bug makes no sense. You told your program:
#pseudo code
if(false and false)
print error
else
print ...
your program is simply obeying the rules you set. The if statement above your else statement will never be reached because the if statement will always evaluate to true.

How does this bool variable work exactly?

I am new to programming, so please forgive me if my question is too basic.
For the following code, I don't know how exactly the bool variable "more" works. It says that while loop will do the content of the loop whenever the "more" is true, but
how does the computer know that the more is true? Is it smart enough to know that "more" literally means when the user inputs additional value through keyboard? Also, does it know that a negative input is not considered "more" but only positive input is considered "more"?
Inside the while loop, it says that the more is false when the input value is 0. However, it does not logically make sense that more is false when it already goes through the while loop, which only runs when the more is true!
I learned that we will get an infinite loop when "while is always true". It seems like the while loop will always be true since more = true.
Please help me out with this question!!
vector<double> salaries;
cout << "Please enter salaries, 0 to quit:" << endl;
bool more = true;
while (more)
{
double s;
cin >> s;
if (s == 0)
more = false;
else
salaries.push_back(s);
}
(1): The computer (or the compiler) is not smart enough to connect more to a literal meaning.
(2): more can be changed inside the loop, which is what happens when you enter 0. After changing more to false, the condition in while (more) is re-evaluated. As more is now false, the loop is exited.
(3): No, more is not always true, see (2).
Ok, so point by point:
1) The compiler knows that more is true because on line 3 it says:
bool more = true;
This creates the bool more and gives it the value true.
2) more is then set to false if s is equal to zero. Although more is true at the beginning of the loop there is nothing to say it can't be changed within the loop (this is called mutability).
3) Because more gets set to false within the loop, the loop will stop executing. This will only happen if someone enters 0 for the input. If this doesn't happen you are correct, the loop will get run forever.
This is a fairly common while loop construct which allows an arbitrary number of values to be added to the vector salaries. In your question you hint that positive numbers should not be allowed, it is worth noting that there is nothing in the code enforcing this. Perhaps it would be better to change the line:
if (s == 0)
to:
if (s <= 0.0)
This way the loop will stop executing if a 0 value is entered or if a negative value is entered.
In your code snippet variable more is explicitly set two times: before the loop and inside the loop if s is equal to zero
bool more = true;
while (more)
{
//...
if (s == 0)
more = false;
//..
}
Thus when more will be set to false within the body of the loop
if (s == 0)
more = false;
the loop stops its iterations because the condition in while will not true
while (more)
Take into account that the condition above is equivalent to
while (more == true)
Though there is no great sense to write such a way because variable more is already a boolean expression.
Also take into account that according to the C++ Standard
4.12 Boolean conversions
1 A prvalue of arithmetic, unscoped enumeration, pointer, or pointer
to member type can be converted to a prvalue of type bool. A zero
value, null pointer value, or null member pointer value is converted
to false; any other value is converted to true. For
direct-initialization (8.5), a prvalue of type std::nullptr_t can be
converted to a prvalue of type bool; the resulting value is false.
You could rewrite your code snippet in other way without using variable more. For example
vector<double> salaries;
cout << "Please enter salaries, 0 to quit:" << endl;
double s;
while ( cin >> s && s != 0 )
{
salaries.push_back(s);
}
Or the condition in while could be written even like
while ( cin >> s && s )
So according to the quote of the C++ Standard if s is not equal to 0 then it is converted to bool true. As for expression cin >> s then class std::istream has explicit conversion operator that converts std::cin to boolean value if the stream is not in erroneous state.
The variable more is explicitly set to true before the loop is entered. In the loop's body, if more is set false, nothing else is executed in the loop's body afterwards. The flow of execution goes again to the beginning of the loop, where the loop's condition is evaluated. As more is false, the loop's body is not executed again.
No, the computer(compiler, more appropriate) does not know the intent behind your coding, specifics behind your variables and functions, It only working on set of instructions, which need to be syntactically correct.
in while(more) it's job is to run the loop for as long as more boolean is true and skip to next instruction when false.
while(condition),here condition is checked once for every iteration, and during the iteration, the compiler does not bother to check and skip the rest of the code upon more being false. the condition is checked only before beginning an iteration.
Absolutely, just assume while(true){set of instructions;} the condition is always true and therefore the block of code is always executed and we call this an Infinite Loop.
Well, it seems that you don't really understand the way your compiler works.
First of all, your computer is not smart or dumb, it's merely a machine and interprets whatever you give them to. So, it all comes to the way you have programmed your program. Having said that we move on:
The
while(condition) {
commands;
}
loop works basically as follows:
It checks the condition whatever that might be at the time it your
program flow enters the loop.
It continues to execute whatever commands are if and only if the previous checked condition was true.
If it wasn't true then your programs continues to execute whatever command follow your while loop.
When the execution of commands have finished it goes again to check the condition in while.
Again, if it's true it carries on with commands.
If not, then again it continues to the following your while commands.
So, to sum up, your compiler, computer or your digital friend does not check for logical flows in how you name your variables, if false does not make sense, etc. It merely checks if condition is true. That's it.
Finally an infinite loop will occur if the initial condition was true when entering the loop and when exiting the loop always continues to be true (not does not change inside the loop because it could change and also get a true values when exiting the loop).
You have some misunderstandings with how things work in C++. You can think of your program as an abstract machine. Each variable is a storage location that maintains some state. The more variable is an example of this state. You can think of the variable as a location in memory that maintains the value that you give it. The total program state is allowed to change throughout the duration of the runtime of the program.
Each assignment (the = operator) sets the state of the variable to the value on the right hand side of the assignment.
So when you say:
bool more = true;
The storage location named more is set to the value true. The storage location will remain true until you assign a new value to it.
Note that in C++ statements are evaluated sequentially. Since the values of the variables may change over time, the order of the statements matters.
Later on when you say:
while (more)
{
// ...
}
The first time that more is evaluated, it is true, but again, since more is a variable, that value may change over time.
Once you are inside the while loop, the more variable is conditionally assigned false when the variable s is equal to 0. Notice that the == is truly an equality check unlike the = operator.
if (s == 0)
more = false;
Note that you should be aware that s is of type double and the literal 0 is of type int. Fortunately for you, this will work since C++ will automatically promote the int to a double type to do the equality comparison. However, it probably makes since to use a literal 0.0 to be clear that you expect for s to be a double.
Since the value of s is dependent on the value that is read from cin, the equality condition will sometimes be true and sometimes false depending on what is entered by the user. But if more is assigned false, it when then cause the while loop to terminate on its next iteration. In other words, when you reach the close brace } the program will repeat back to the beginning of the while and try to re-evaluate more, at that point, when more is false the while loop will end.
vector<double> salaries;
cout << "Please enter salaries, 0 to quit:" << endl;
bool more = true;
while (more)
{
double s;
cin >> s;
if (s == 0)
more = false;
else
salaries.push_back(s);
}
A while loop will iterate over and over until the condition between the ()is not met. When you start the cycle you start with bool more = true; That way you're telling the while(more) loop to keep iterating while more is true. Inside the code you ask for input with cin >> s; and if the input is 0 the variable more will change to false, it will iterate again and since while(more) is awaiting for the morevariable to be true the condition won't be true and the cycle will end. If you input other value than 0 the cycle will store that value into the vector<double> salaries vector.
One way for getting the values that were stored in the vector is:
for(int i = 0; i<salaries.size(); i++){
cout<< salaries[i] << endl;
}
In which case you're telling the compiler to iterate with a variable called i starting from the value 0 until the value of i is < than the value of salaries.size(), for each iteration, i will increase and when the condition is no longer met, the cycle will end.
As a recomendation, use the std namespace for your types, it will be of help in future code to avoid bringing everything from the std namespace into your code.
std::vector<double> salaries;
std::cout << "Please enter salaries, 0 to quit:" << std::endl;
bool more = true;
while (more)
{
double s;
std::cin >> s;
if (s == 0)
more = false;
else
salaries.push_back(s);
}
and
for(int i = 0; i<salaries.size(); i++){
std::cout<< salaries[i] << std::endl;
}

Access violation reading location 0x00000006

I have the following code which finds the strings that contain no Alphabets. Cases like mynumber123 shall not be recognized and the numberFinder() should return false and case like 123 shall be recognized and numberFinder() shall return true as well as the begin index of the number.
the constructor:
CaddressParser::CaddressParser(string fileName) //constructor
{
m_fileName=fileName;
int length=getLength(m_fileName.c_str());
m_text =fileReader(m_fileName.c_str());
m_length=length;
}
which initializes a string m_text that contains the contents of a text file
Somewhere along the implementation I come across the following code:
for (i;i<m_length;i++)
{
bool UpperCaseBeforeNoFound=false;
if(this->numberFinder (i).second)
{
//do some calculations.
}
}
the numberFinder function is implemented as follows:
pair <int,bool> CaddressParser::numberFinder(int counter)
{
bool noFound=isdigit(m_text[counter]); //number found? -> true
if(noFound)
{
int end=HouseNoDigits(counter);
if(((counter-1)>=0) && ((counter +end-1) <m_length))
{
if((!(isalpha(m_text[counter-1]))) && (!isalpha(m_text[counter+end-1])))
{
return make_pair(counter,noFound); //return index if true
}
}
}
else return make_pair(0,noFound);
}
Now the problem is for a text file containing the following text "he23 Market street London Q12 H13". I get the error mentioned in the headline and the debugger takes me to the line in the which contains :
if(this->numberFinder (i).second)
I can't figure out why this is happening. Please help me figure it out.
If this condition in CaddressParser::numberFinder(int counter) fails:
if (counter - 1 >= 0 && counter + end - 1 < m_length)
the function will exit without returning a value, resulting in undefined behavior.
The complexity of the conditionals in the function isn't helped by the poor formatting (at least as posted in the question).
You might get the behavior you need by removing the else so any 'fall-through' will return the default pair value (but that will depend on if that's the value you want to really return in that scenario):
pair <int,bool> CaddressParser::numberFinder(int counter)
{
bool noFound=isdigit(m_text[counter]); //number found? -> true
if(noFound)
{
// ...
}
return make_pair(0,noFound);
}
Access Violation error is normally due to NULL reference. One of the function that you are calling is trying to access a NULL pointer. Make sure your isdigit function returns true or false, m_text points to an exiting memory location. If not you need to allocate the memory. You should also check if the fileName is NULL.