c++ - 字符串操作 C++ 在字符串后存储整数

标签 c++ string

我正在尝试操作一个字符串(如下)。我如何将“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 seperate string, 1 in an int, 2 in an int, and 3 in a double?

更容易将字符串拆分成多个部分的方法是使用 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/

相关文章:

c++ - 检查函数体是否为空

regex - 检查当前单词之前是否有多个单词

c++ - 如何在 C++ 中进行快速字符串连接

javascript - 字符串到数字 JavaScript

php - UTF8 字符串上的 == 安全吗?

java - 在第一列中查找重复项并根据第三列取平均值

c++ - 后缀表示法计算器 (RPN) 问题 C++

c++ - 如何使用 Boost.Program_options 实现子命令?

c++ - 通过 SWIG 从 C++ 调用 Go 回调函数

c++ - 将 vector 输出到屏幕?