Using value of variable as a name next variable in C++ [duplicate] - c++

This question already has answers here:
How can I make a integer for every name in a txt file?
(4 answers)
Closed 7 years ago.
I have one question about C++.
I would like to use value of variable as a name of next variable.
Example:
User write value
cin>>PlayerName;
//PlayerName = 'John';
Now app should add +1 to variable "John"
John=John+1;
How to do that?
Regards

You cannot do this in C++ (At least not without crazy hackery). What you are trying to do is "reflection" - to edit your program during runtime. This is very easy in Python, but requires shenanigans in C++.
To answer the spirit of your question, which is "How can I programmatically edit things based on user input" is to use a map, as Neil Kirk suggested, where they key is a string.
Then you'd do something like
std::map<std::string, int> playerScores;
playerScores["john"] = 0;
cin >> playerName;
playerScores[playerName] += 1;

Related

How to approach .startswith() in C++? [duplicate]

This question already has answers here:
Check if one string is a prefix of another
(14 answers)
How do I check if a C++ std::string starts with a certain string, and convert a substring to an int?
(23 answers)
Closed 1 year ago.
I'm new to C++, learning from books and online video tutorials. I've been trying to get the following lines of code to work, without much success. Basically, trying to find a C++ equivalent to python'a .startswith() or "in".
In python, what I'm trying to achieve would look like this:
names = ["John","Mary","Joanne","David"]
for n in names:
if n.startswith("J"):
print(n)
In javascript, the syntax would be quite similar (there are better ways of doing this, but I'm trying to keep the lines of code close to python's):
const names = ["John","Mary","Joanne","David"];
for (let n of names) {
if (n.startsWith("J")) {
console.log(n);
}
So, I assumed things would work similarly in C++, right?
vector <string> names {"John","Mary","Joanne","David"};
for (auto n: names) {
if (n[0] == "J") {
cout << n << endl;
}
As I've just started learning about pointers, I might be getting confused between types / values / addresses, apologies for this.
What's the best way to solve this please? Alternatively, how should I find a way to mimic what "in" does in python, but for C++?
names = ["John","Mary","Joanne","David"]
for n in names:
if "J" in n:
print(n)
Thanks!

Expression must have a constant value error in an array with the size input by user [duplicate]

This question already has an answer here:
Passing an int to a function, then using that int to create an array
(1 answer)
Closed 4 years ago.
So i have this code, part of a larger function.
int size, j;
cout << "Enter the size of array" << endl;
cin >> size;
float b, n[size];// error
and I get the already famous E0028-expression must have a constant value. Now I saw people getting around this with "new int" and while I kinda understand the concept of it, technically I have not learned this type of int, not yet,nor objects etc. Also where I'm learning c++ they tell me that this should work just fine. I use visual studio enterprise 2017 to code(maybe there is a problem on my end with the compiler). Basically what I want is an array that has the size of it decided by the user input. And yes I know it wants to have a const and not a variable value. What are any work-arounds this ? (answer like you would try to teach your dog programming please because that is where my knowledge lies). Thank you.
Edit: While I see people trying to tell me use std::vector(that again i technically did not learn but kinda understand the concept of it) the people from the place where i'm learning c++ are telling me it should work that way.I did read a bit about the error before asking the question and saw some related stuff about the c99 standard( 2 much stuff to make a wall of text here). So the follow up question is: are they teaching outdated ways of writing this stuff ?
Thank you.
Variable length arrays, such as n[size], are not supported by standard C++, although some compilers allow it as an extension. (Note that C allows it, although it was made optional in C11.)
Use std::vector<float> n(size); in your case instead. That will allow you to access elements of n using []; e.g. n[0] is the first element.
As a rule of thumb, use a std::vector to model an array of a numeric type, unless you can think of a good reason not to.
The error is selfeplanatory: you cannnot use non-const expression in float n[size];.
In your case you need to use new operator or use one of standard containers: std::array or std::vector if you want to change the array size later on.

What is the best way to convert a string type to an int type as Industry standard? [duplicate]

This question already has answers here:
How to parse a string to an int in C++?
(17 answers)
Closed 6 years ago.
In C++, what is the best way to take input string and convert it to a number type. I was messing around with literal strings and was having a difficult time doing this, I am imagining that using a C String is easier? What is the best way for co-workers and fellow students to follow and make it easy and simple? Any thoughts?
What is the industry standard on this? Using STOI?
Look at the following example:
std::string numberString = "125";
int number = std::stoi(numberString ,nullptr);
It can convert an std::string to int

C++ Using strings to access variables [duplicate]

This question already has answers here:
Access variable value using string representing variable's name in C++ [duplicate]
(8 answers)
Closed 7 years ago.
Suppose I have a structure bbox containing 6 sets, where each set contains 4 vectors. I can add a vector element by using bbox.set1.vect1.push_back(foo). However, I'm reading data from a file and I'm looking for an elegant way to store the data in the vectors. Using a double for() loop with indices i (1 to 6) and k (1 to 4) I've tried the following (using string concatenation):
string test1 = "bbox.set";
string test2 = ".vect";
string fin = test1 + to_string(i) + test2 + to_string(k);
fin.push_back(val);
Though the code compiles fine, nothing seems to happen. Explicitly writing bbox.set1.vect1.push_back(foo) does work. Can this be done in such a way? In another topic I've read that C does not support changing/creating variable names during runtime, but here I simply try to access an existing variable.
No, C++ does not support this, since variable names are resolved at compile time, which means that by the time the program runs, the variable names themselves are meaningless. (In other words, the name bbox has in practice been replaced by a set of numbers representing the object called by that variable name.)
If you really need to something like this, you should consider using a container such as std::map, which you can use to map strings to objects. You can't access them like variables, though, but you can dynamically build strings to decide which object to get.
What you are looking for is some method of reflection, which C++ does not natively support. There is no way to do what you want directly.
Instead you will need to provide your own support.

C++ equivalent of Java Enum.valueOf() [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Is it possible to define enumalpha?
Is there any equivalent of Java Enum.valueOf(string) on C++?
There's no table of names generated by the compiler (unless you count debug information), but if you create one (or use e.g. doxygen which parses the source code and can output such lists in XML format) then you can use a dictionary of some type, such as std::map<string, int> to turn an identifier into its numeric value.
No, there isn't even the much simpler task of going the other way (enum to string), you'd need to write it yourself