1

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(' '));
Cory
  • 23
  • 1
  • 8

2 Answers2

3

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

user0042
  • 7,917
  • 3
  • 24
  • 39
2

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;
DSC
  • 1,153
  • 7
  • 21
  • @user4581301 Go ahead. It's my first time answering. – DSC Nov 22 '17 at 00:12
  • 1
    The formatting magic in answers is to use four space intent rather than the ` character. Have a line before and after the code and don't try to put intended code after a numeric list. For some reason lists screw up the rendering. – user4581301 Nov 22 '17 at 00:15
  • @CedricDeSchepper One little nitpick (technically you're correct). The OP asked for specific variable names and types. Best you reflect such in your answer, before seeing the OP coming up with complaints your code doesn't match their question. – user0042 Nov 22 '17 at 00:20
  • @user0042 haha, nah, I'm not an idiot. Thank you guys very much. One last question, I assume I need an import to use stringstream? – Cory Nov 22 '17 at 00:26
  • @Cory #include will do the job – DSC Nov 22 '17 at 00:28
  • @Cory The import (`#include `) is mentioned in the reference link I provided in my answer. I never had any doubts about your intelligence, sorry if I sounded like so. It was merely a good advice for the (_beginner_) answerer here. – user0042 Nov 22 '17 at 00:38