Cory
Cory

Reputation: 21

string manipulation c++ storing ints after string

I am trying to manipulate a string (below). How would I put "John" in a seperate string, 1 in an int, 2 in an int, and 3 in a double? I figured out how to get John from it.

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(' '));

Upvotes: 1

Views: 63

Answers (2)

user0042
user0042

Reputation: 8018

How would I put "John" in a seperate string, 1 in an int, 2 in an int, and 3 in a double?

Way easier to split a string into parts is to use std::istringstream instead of 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;

Closely related post: The most elegant way to iterate the words of a string

Upvotes: 3

DSC
DSC

Reputation: 1153

In this case I would make use of std::stringstream :

std::string name;    
int wins; int losses;     
double winLossRatio;
std::stringstream ss(s);    
ss >> name >> wins >> losses >> winLossRatio;

Upvotes: 2

Related Questions