I want to get player name from Chat log. Now I just need to find it from this line (param 1: `5<`2player`` entered, `w1`` others )
1 2 3 4 5 6 7
std::string str="param 1: `5<`2PlayerNameIwant`` entered, `w1`` others here>``";
std::size_t pos = str.find("2"); // position of "2" in str
//but I don't want the stuff after "``" to be in my string.
//not sure how to proceed, only done 2 days of c++.
#include <sstream>
#include <string>
#include <iostream>
int main()
{
const std::string str {"param 1: `5<`2PlayerNameIwant`` entered, `w1`` others here>``"};
std::istringstream param(str);
std::string name;
std::getline(param, name, '2'); // Just to read and discard up to the 2. Could be .ignore() but getline() easier
std::getline(param, name, '`');
std::cout << name << '\n';
}
You have a good start to find the "2". Now do the same to find the (`). Be careful with that (`) it is not the same as the ASCII ('). It did work in MSVS 2017 when I tested it, but for some it may not.
What you can do:
1 2 3 4 5 6
std::string str = "param 1: '5<'2PlayerNameIwant`' entered, 'w1'' others here>''";
std::size_t first = str.find("2");
std::size_t last = str.find("`");
std::cout << "\n " << str.substr(first + 1, last - first - 1) << '\n';
For line 6 take out the (+ 1) and (- 1) and see how that changes the output.
@Andy. Not quite. Your L1 isn't the same as that of the OP. In the OP all are ` there are no '. You then need to start the find for ` starting from the position the 2 was found. Also, you need to check that 2 has been found. As C++17:
1 2 3 4 5 6 7 8 9 10 11 12 13
#include <string>
#include <iostream>
int main()
{
const std::string str {"param 1: `5<`2PlayerNameIwant`` entered, `w1`` others here>``"};
if (constauto first {str.find('2')}; first != std::string::npos) {
constauto last {str.find('`', first)};
std::cout << str.substr(first + 1, last != std::string::npos ? last - first - 1 : last) << '\n';
}
}
I noticed that, but I have had trouble with the (`) in the past. Also had trouble with the double quote of the same type. After changing back to OP original string I found that it still worked, but by then he appeared to be finished.