ddog ddog - 2 months ago 9
C++ Question

How to keep the value of a string?

Hey guys I have a question about variables and If statements.

The reason I am asking is I am assigning tokens in a vector of strings to variables but if my vector only has 3 elements and I try to assign a variable to myVector(5) I get an error.

This is my solution to that problem

std::string element5;
if(myVector.size () >= 4)
(
std::string element5 = myVector.at(4)
}


But that wont change the string outside the if statement? My code works fine if I have exactly 5 elements and no error check but if I'm passing in standard input I wont really know how many elements there are all I will know is that there are a max of 50 elements.

I dont need to ouput any elements just run this code on each one

if(countSubstring(element5,"a") > 0)
{
a = a + 1
}


then I would output a.

how do I make element5 keep its new string?

Answer

Problem

Your code here redefines your variable element5:

std::string element5;
if(myVector.size () >= 4)
(
    std::string element5 = myVector.at(4)
}

Here you first declare element5 after the first line, and then you re-declare it at the third line in your if statement. That essentially "recreates" the variable element5 for that scope {}. And then of course is poped right after the scope. So you won't see a change in element5 if you try to print it out of the scope.

Solution

Easy, just don't re-declare your variable, and you're all set! Like so:

std::string element5;
if(myVector.size () >= 4)
(
    element5 = myVector.at(4)
}

Why is this happening?

Like I said, down in the assembly level the variable gets pushed, and then suddenly when it comes down to another level and the same variable gets re-declared, the global variable gets forgotten about. And as soon as the scope ends:

{
  //This is a scope
}

the re-declared variable gets poped off the stack, and we have our original element5 back! This will leave element5 in the same position since you didn't actually change it ;).

Undefined Behaviors(UB)

Don't reference to an out-of-scope object; don't do it!

C++: Reference to "out of scope" object

References

What happens when C++ reference leaves it's scope?

What happens in C++ when I pass an object by reference and it goes out of scope?

Glossary

scope: The "container" a program is currently executing under; for example, let's take this:

int main() {
  //1st scope
  if (true) {
    //2nd scope
    {
      //third scope
    }
  }
}

Undefined Behavior(UB): When in an undefined/unknown state at any time given during the compilation. Compiler does whatever it decides to do, making it a very dangerous Behavior especially if you are writing a big project! Here is a good question/answer to this topic:

http://programmers.stackexchange.com/questions/99692/philosophy-behind-undefined-behavior