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

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!

Related

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

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;

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.

How can I concatenate an int to a string? [duplicate]

This question already has answers here:
How to concatenate a std::string and an int
(25 answers)
C++ int to string, concatenate strings [duplicate]
(6 answers)
Closed 8 years ago.
I have done a good hour or so of research, but I can't find a method that works for me that I actually understand, as I don't understand how buffers work. I've tried the to_string method, I've tried the .append() method, and obviously, a simple concatenation method.
My code:
fileLog[fileLogIndex].append(playerTurn+":"+moveColumn);
//fileLog[fileLogIndex] += playerTurn && ":" && moveColumn && ", ";
So. The purpose of this, or my idea, was to keep track of each move in a connect 4 game I wrote today. This was supposed to append each move, in the format aforementioned. PlayerTurn is stored as an int, 1 being player 1, 2 being player 2, and the moveColumn variable is the column that the user selected to drop their piece. If player 1 dropped a piece into column 4, the idea was to append "1:4, " to the variable and then write that line to a file.
As you can see, I have tried a few methods, like append, and even though you can't see, I have tried to to_string () method, but I either get an error, or "1:1" gives me a smiley face in the dos window, or a null in notepad++ when opening the file.
I don't want to use a method I don't understand, so I apologize if this is a repeat of another thread, I'm just tired of staring at this 1 line of code and getting nowhere with the methods I am trying. If I have to use a buffer to do this, fine, but can someone explain to me, in somewhat newbie terms, what each line is doing?
For the record, I am using Visual Studio 2010, and I'm 90% sure I don't have C++11, which I read somewhere is the reason to_string isn't working as expected for me..
The C++ way to do this (i.e., without using C's buffers and sprintf) that doesn't use C++11's to_string is by constructing the string using an ostringstream:
#include <sstream>
ostringstream out;
out << playerTurn << ":" << moveColumn;
fileLog[fileLogIndex] += out.str();

How should I tokenize a string and enter the tokens into a list, using whitespace as the delimiter? [duplicate]

This question already has answers here:
How do I tokenize a string in C++?
(37 answers)
Closed 8 years ago.
I have taken many looks, but I have not been able to find a working snippet which I would understand at my current learning level. What I'm aiming to do is again:
Take input:string input = "Eggs and Spam";
Tokenize it, and then put the tokens (together) into a list: Which I see as this: inputlist = ["Eggs", "and", "Spam"];
First, I may like to know how to (hopefully briefly) declare a list, and do the above by appending the list.
In terms of C++, I'm also curious how I could do so when using only the default libraries, as I am having trouble handling library files at the moment.
The easiest way is using Boost's Strings Algorithm library - http://www.boost.org/doc/libs/1_55_0/doc/html/string_algo/usage.html#idp206847064
Then it's as easy as:
vector<string> parts;
split( parts, "Eggs and Spam", is_any_of(" "), token_compress_on )

How do I split a string into two strings using a comma, and store the strings? (C++) [duplicate]

This question already has answers here:
How do I iterate over the words of a string?
(84 answers)
Closed 9 years ago.
I looked to see if this had been asked before, but all I got was answers for Java. I have to read first names and last names from a file, in the format of (lastname,firstname). The program requires us to (among other things), display the name in the format of (firstname lastname), with a space instead of a comma. I figured the easiest thing to do would be to split the string into two smaller strings, and then just display them in order. How would I go about doing this? I saw some BOOST token thing, but I can't use that as the program has to be able to run on vanilla CodeBlocks.
Certainly more compact, if not more elegant solutions are possible, but this does it--
#include <string>
//... read input_str from the file
int pos = input_str.find_first_of(',');
std::string firstname = input_str.substr(pos+1),
lastname = input_str.substr(0, pos);
std::string output_str = firstname + " " + lastname;