Variable not accessible within an if statement - c++

I have a variable which holds a score for a game.
My variable is accessible and correct outside of an if statement but not inside as shown below
score is declared at the top of the main.cpp and calculated in the display function which also contains the code below
cout << score << endl; //works
if(!justFinished){
cout << score << endl; // doesn't work prints a large negative number
endTime = time(NULL);
ifstream highscoreFile;
highscoreFile.open("highscores.txt");
if(highscoreFile.good()){
highscoreFile.close();
}else{
std::ofstream outfile ("highscores.txt");
cout << score << endl;
outfile << score << std::endl;
outfile.close();
}
justFinished = true;
}
cout << score << endl;//works
EDIT:
have realised my problem, when I was printing out it looped through many times so I did not see that all of them for the first loop didn't work, hence I thought the others were working when in fact they were not for the first iteration.

This is not a problem relating to the scope of the variable.
It could be several things:
Memory corruption somewhere
Multi threading relating problem
Something else...
Are you sure you are looking at the same iteration where the score value works before and after but not inside? Maybe put some more detailed logging instead of simply outputting the score itself.

Try printing cout << score << "#" << &score << endl; each place you currently print score. This will let you check if you're actually looking at the same variable.
If the addresses are different, you're accidentally shadowing your score variable somewhere - gcc has -Wshadow to catch that.
If the addresses are the same then the variable is getting corrupted somehow. Most debuggers have a memory breakpoint feature, so you can set the debugger to break when the memory in score changes and find the culprit.

With the amount of code you have attached there is nothing to indicate there is a problem in the code. As Brian says it is something else
Can you try this in your debugger and see what happens ? The idea is to simplify the problem as much as possible and try to get the minimal amount of code that replicates the problem.
What does this do ?
cout << score << endl; //works
if(!justFinished)
{
cout << score << endl; // doesn't work prints a large negative number
}
cout << score << endl; //works

Related

When I run the program in DevC++ 5.11 TDM-GCC 4.9.2 doesn't work how I expect, but in an online compiler it just works [duplicate]

This question already has answers here:
Uninitialized variable behaviour in C++
(4 answers)
Closed 2 years ago.
I'm a newbie in the programming world, and i've decided to start with C++ code a few days ago as my first programming language.
I just started to read an online course which i'm guiding on (and aply while i'm reading it).
The course in question assigns a serie of small optional exercises, wich go hand in hand with the topic that is being dealt at that moment.
One of this optional exercises is: "Create a program that multiplies two whole numbers in the following way: it will ask the user for a first whole number. If the number that you type is 0, it will write on the screen "The product of 0 by any number is 0". If a number other than zero has been entered, the user will be prompted for a second number and the product of both will be displayed."
How it says, I did my best to coding that program.
The code of what I did is:
#include <iostream>
using namespace std;
int main ()
{
int a;
int b;
int solve;
cout << "Enter a number: ";
cin >> a;
if (a!=0)
{
cout << "Enter another number: ";
cin >> b;
}
if (b!=0)
{
solve = a * b;
cout << "The result of your operation is: " << solve << endl;
}
else cout << "The product of 0 by any number is 0." << endl;
return 0;
}
So, I press F9 to compile, then F10 to run it.
I proceed to testing it.
I put and different number from zero, I put another one. Throws me a multiplication of both. Nice.
I put and different number from zero, I put another one that actually its zero. Throws me the message of "else" order. Nice.
**BUT
I put and number equal to zero, and throws me the message of the "cout" order of "if (b!=0)".**
I didn't really know what I had done wrong, so, I ask for help from a friend who has some more experience than me, and tells me that actually it's nothing wrong. In fact, he proved me sending to me a screen cap of his Dev C++ with my code in it, and how it runs just how it had to be.
Then, I opened an online compiler (https://www.onlinegdb.com/online_c++_compiler#) to get down my doubts, and yes, there runs correctly too.
So, here's my question?
What's the problem? Why that happens?
I have the DevC++ 5.11 TDM-GCC 4.9.2, and I'm using the deafult compiler.
Please, I would like some of help, I feel more comfortable compiling in PC than online, it's more quick.
Thank you anyway for reading until here.enter image description here
The reason why this happens, as #TrebledJ mentioned, is that you've not initialised the variable b. So you can get over this problem just by initialising b to any value of your choice (preferrably 1 or 0 for simplicity). But there's a workaround if you don't want to initialise the values. I would transform your code to something like this:
if (a!=0)
{
cout << "Enter another number: ";
cin >> b;
if (b!=0)
{
solve = a * b;
cout << "The result of your operation is: " << solve << endl;
}
else cout << "The product of 0 by any number is 0." << endl;
}
else cout << "The product of 0 by any number is 0." << endl;
Basically, what I'm doing is, if the value of a after input is 0, I'm not running the part for taking the user input of b.

Baby names popularity program

I have to write a program that allows the user to input a name from the keyboard. The program should then read from the file and search for matching name among the girls and boys. If a match is found it should output the rank of the name. The program should also indicate if there is no match.
Here is my program :
ifstream fin;
fin.open( "/Users/fashiontekk/Downloads/Assignment 3 Instructions/babyNames2017.dat" );
string nameInput;
string boyName;
string girlName;
int rank= 0;
int boyRank= 0;
int girlRank =0;
cout << " Which name would you like to check? < no space in names please > " << endl;
cin >> nameInput;
fin >> boyName;
fin >> girlName;
rank++;
cout << " After going through an extensive search here is what we found out - " << endl;
if (nameInput == boyName) {
cout << nameInput << " is ranked " << rank << " in popularity among boys. " << endl;
boyRank = rank;
}
if (nameInput == girlName) {
cout << nameInput << " is ranked " << rank << " in popularity among girls. " << endl;
girlRank = rank;
}
if (boyRank < 1 || boyRank > 1000) {
cout << nameInput << " is not ranked among the top 1000 boys name. " << endl;
}
if (girlRank < 1 || girlRank > 1000) {
cout << nameInput << " is not ranked among the top 1000 girls name. " << endl;
}
cout << " Hope that is the result you were looking for ... Ending program. " << endl;
fin.close();
return 0;
}
However, my output window says : Which name would you like to check? < no space in names please >
Program ended with exit code: 0Liam
After going through an extensive search here is what we found out -
Liam is ranked 1 in popularity among girls.
Liam is not ranked among the top 1000 boys name.
Hope that is the result you were looking for ... Ending program.
I tried to type in Liam which the most popular boys name according to the file provided. I feel like my coding is right however I can't spot the error.
It is my first year in Computer Science and I don't can't find my mistake.
OK, we've all been there at some point. You need to work on your debugging skills — you're gonna need them. In particular, spend some time learning to use gdb or whatever debugger you have available. A good debugger will let you step through a program a line at a time, watch variables, and generally checkout every possible thing that could be a problem.
So let's take a look at your code with an eye toward debugging it. It's handy that the message that's emitted comes right up near the top of the program — that really narrows down the places where you could be going wrong. Here's the first part of your program:
ifstream fin;
fin.open( "babyNames2017.dat" );
if (!fin) {
cout << " File not processed ";
return 0;
}
So, the first line just declares the variable for your input file. There's not much that can go wrong there. The next line opens the file... hmmm... I'm not sure if that might be a problem or not, so let's stick a pin in it for now and keep going. The next line, if (!fin) {, is a condition that only succeeds if !fin is true, which means that fin must evaluate to false to enter this block. And it clearly does enter this block, because that's the part of the code that emits the "File not processed" message. So fin must be 0, right? OK, so how can fin possibly be 0?
I don't have the C++ iostreams documentation handy, but you should go look up what that fin.open(...) call does if it fails. Given the way you've written the code, it looks very much like you'd expect failure to set fin to 0, right? So how can that call fail? Well, for starters, you're only supplying the file name... the working directory when you run the program might be set to something you don't expect, so the file isn't found. Or the file name might not match the name of the actual file. Remember that some file systems are case sensitive, and if you're working with such a file system then the open call will fail if the file is just named babynames2017.dat or BabyNames2017.dat or anything else that doesn't exactly match your file.

Do-while loop running twice when it should run only once (C++)

friends. I have a problem.
Problem: the computer must pick randomly one string out of an array of 36 strings. If by any chance it picks strings #34 or #35 (the two last ones), it has to draw two more random strings from the same array. I tried a do-while solution, and it "almost" works (see code below).
The randomization works fine - called srand inside main(). There is a forced "x2" draw (for testing reasons), so the computer draws two more strings. These two new random picks are NOT "x2", but still the loop kicks again - but just one more time! This time the computer picks two more "chits", which aren't "x2" either, so, as expected, it returns the "The chits have been drawn" sentence and the function is terminated. Why is the same code running twice with the same results but different if/else behavior? Thank you very much in advance.
string mortalityCalc ()
{
string mortalityChits[36] = {"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","-","-","-","-","x2","x2"};
int mortalityResult;
// mortalityResult = rand() %36;
mortalityResult = 35; // for testing only. Delete afterwards.
string drawnChit = mortalityChits[mortalityResult];
string drawnChit1;
string drawnChit2;
if (drawnChit != "-" && drawnChit != "x2")
{
string returnText = string("The computer has drawn the chit '") + drawnChit + "'.";
return returnText;
}
else if (drawnChit == "-")
{
string returnText = string("The computer has drawn the chit '") + drawnChit + "'. No senators died this year.";
return returnText;
}
do
{
cout << "The computer has drawn the 'x2' chit." << endl;
cout << "Two more chits will be drawn.\n" << endl;
mortalityResult = rand() %36;
drawnChit1 = mortalityChits[mortalityResult];
cout << "The first draw is the chit '" << drawnChit1 << "'. ";
mortalityResult = rand() %36;
drawnChit2 = mortalityChits[mortalityResult];
cout << "The second draw is the chit '" << drawnChit2 << "'." << endl;
} while (drawnChit1 == "x2" || drawnChit2 == "x2");
return "The mortality chits have been drawn. The corresponding senators are dead.";
}
UPDATE: Tried running this code isolated from the rest of the program and it behave as expected. So I guess it's important to post what comes before it:
cout << "If you are a lazy bastard, the computer can pick one senator randomly for you.\nAre you a lazy bastard? [y/n]" << endl;
string lazyBastard;
cin >> lazyBastard;
cout << endl;
if (lazyBastard == "y" || lazyBastard == "Y" || lazyBastard == "yes" || lazyBastard == "YES" || lazyBastard == "Yes")
{
mortalityCalc ();
cout << mortalityCalc () << endl;
cout << "Very well. Now, imminent wars become active (Only one of each match)." << endl;
cout << "Get ready for the next phase." << endl;
My guess, from reading some other questions here, is that somehow the cin is messing with the loop behavior, even though they are not related and there's no user input whatsoever in the loop's statements or conditions. Is that possible? If so, why and how to remedy it?
Thank you again.
In the first loop you are forcing an 'x2' so your are entering the do-while loop. The result of the two calls for 'rand())%36' is always 19 and a number between 30 and 34. The point is that the random number generator generates always the same sequence of numbers, if you don't give him a seed 'srand(...)'.
do {
// ...
cout << rand()%36;
// ...
} while( /*...*/ )
See http://ideone.com/zl8ggH
You have to create random numbers and your code does what you expect.
Finally! I thought it would be a stupid thing! I just realized that I called the mortalityCalc() function twice! That's why it was looping twice!
Thanks to all who tried to help!

Visual C++ - Runtime Check Failure #3 - Variable is not initiliazed

I use Visual C++ 2010 Express Edition to compile and run the .exe files I write in the C++ programming language. I am trying to create a loop-based logic using C++ to ask the user how many entries he chooses to enter, and ask questions limited to that no. of entries. For example I want to output, "How many characters do you wish to enter?: " Say the user gives the answer as '3' which is stored in the int variable 'entries'. I then want to keep asking the question 3 times before it stops and continues with the next line of code. I hope you understand, here is a block of code to demonstrate what I am doing:
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "How many values do you need to enter?: ";
int entries;
cin >> entries;
int offset, number;
string valueName[50];
float valueValue[50];
for (offset = 0; offset < entries; offset++)
{
cout << "Enter " << number << " Value Name: ";
cin >> valueName[offset];
cout << "Enter " << valueName[offset] << "\'s value: ";
cin >> valueValue[offset];
for (number = 1; number <= entries; number++)
{
}
}
char response;
cin >> response;
return 0;
}
Strangely when I run this simple program, it fails when I enter the value's name to be inserted into the 0th element of the valueName[] array. It just pauses the execution of the program and a dialog box pops up saying "Runtime Check Failure #3 - Variable 'number' is being used without being initialized!" Another problem regarding this program is that, for quite some time, when I ran this program this "Runtime Check Failure #3" box never appeared, and when it didn't, the number value went wrong, and first started with 1, and then for the next loop jumped to 6, and then repeated 6 again for the next loop! Please help me! I've checked online scouring this problem everywhere, but it just doesn't apply to my type of problem! Is it because the variables are out of scope? But they're declared outside the for loops right? So please help me!
The runtime is telling you the truth, the following line comes after you have declared number as an int but have not given it a value.
cout << "Enter " << number << " Value Name: ";
In your code you declare the following, in C++ this means give me 2 ints but the values are not defined yet, e.g.
int offset, number;
Change it to something like this ..
int offset = 0;
int number = 0;
You are printing the variable number without assigning to it first, i.e. it's uninitialized. When it prints some random number it's because that what happens to be in the memory at the time you run the program. Assign a value to it before you use it.
The problem is exactly the error message you're getting. You're using the variable number without initializing it.
You use the variable right here, at the top of your loop, when it hasn't been initialized to anything yet:
cout << "Enter " << number << " Value Name: ";
What is your intention with the number variable? It doesn't really seem to be serving any purpose. If you want to print which entry you're currently on, you could use the offset variable instead, like this:
cout << "Enter " << offset << " Value Name: ";
But that still seems a little unclear to me.
But the reason that you're having a problem is because the value is uninitialized, so you're experiencing undefined behavior. This is also the reason that Visual Studio doesn't always catch it; it will probably always catch in Debug mode, but in Release mode it will almost never catch it. You need to initialize all your variables before you use them.
In my case it was because an extern variable was declared twice.

C++ For Loop not Exiting

I have a for loop, a very simple one, in my program, and I want it to loop through and do something for some minimum number of times. However, the loop simply...stops. But does not move on to the next thing in the program. For instance, when min is 9, it runs for i=0 to i=8, then freezes. It should exit the for loop, but it does not execute the next print instruction, nor does it execute the loop again. It just stops. The program hangs, doing absolutely nothing as far as I can tell. I don't understand why this is.
The merged.put() function I want to execute just puts x or y in merged, depending on the condition. That part works. This is just a small part of a much larger program. sp1, sp2, and merged are all defined elsewhere.
int i;
int x;
int y;
for(i=0; i < min; i++)
{
cout << " here " + convert(i);
x = sp1.get_num(i);
y = sp2.get_num(i);
if(x >= y) {
merged.put(x);
}
else {
merged.put(y);
}
cout << " end" << endl;
}
cout << "out";
EDIT: I'm not posting the entire code, it's several hundred lines long. Type of min is int. The reply down there was helpful, when << endl was added to the last print statement, it printed. My problem now appears to be here, getting stuck on the second while, because I was not incrementing i. Shame on me...thanks for the help. (This comes directly after the above code)
if (sp_large == 2) {
cout << "1" << endl;;
while (i < sp2.get_size()) {
merged.put(sp2.get_num(i));
}
}
else {
while (i < sp1.get_size()) {
merged.put(sp1.get_num(i));
}
cout << "2" << endl;
}
EDIT: Problem solved, thanks for the help.
I'm betting that it's actually a later part of the program that is hanging.
This line:
cout << "out";
just puts "out" on the output-buffer, and won't actually print "out" until the output-buffer gets flushed. (Which could happen immediately, but is not likely to.) Change that line to this:
cout << "out" << endl;
and "out" will be printed as soon as that line is run. This will help you figure out if the program is hanging before it gets to that line, or somewhere later on.