我正在尝试操作一个字符串(如下)。我如何将“John”放入单独的字符串中,将 1 放入 int 中,将 2 放入 int 中,将 3 放入 double 中?我想出了如何从中得到约翰。
string s = "John 1 2 3";
string name = s.substr(0, s.find(' '));
string wins = user.substr(playerOne.username.length(), user.find(' '));
string losses = user.substr(wins.length(), user.find(' '));
string winLossRatio = user.substr(losses.length(), user.find(' '));
最佳答案
How would I put
"John"
in a seperatestring
, 1 in anint
, 2 in anint
, and 3 in adouble
?
更容易将字符串拆分成多个部分的方法是使用 std::istringstream
而不是 std::string::find()
:
std::string s = "John 1 2 3";
std::string name;
int wins;
int losses;
double winLossRatio;
std::istringstream iss(s);
iss >> name >> wins >> losses >> winLossRatio;
密切相关的帖子:The most elegant way to iterate the words of a string
关于c++ - 字符串操作 C++ 在字符串后存储整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47424666/