I have been looking around a while, trying to figure out at the very least, how to take a string like "25 from a car accident" and have 25 as a useable integer and "from a car accident" as a useable string. what i'm trying to accomplish is doing this from a text file. I can read and write and everything i just don't know how to take a string and separate it into the 2 components. Help much appreciated. I know this probably isn't that high a priority question :P so thank you for the support.

6 Years
Discussion Span
Last Post by globberbob

Stringstreams might be your best bet here.

#include <iostream>
#include <sstream>
using namespace std;

int main ()
  string bigString, stringAfterNumber;
  int number;

  bigString = "25 from a car accident";

  stringstream ss (bigString, stringstream::in | stringstream::out);

  ss >> number;
  getline(ss, stringAfterNumber);

  cout << number << stringAfterNumber << endl;
  return 0;

Note that stringAfterNumber will be " from a car accident", not "from a car accident". Depending on whether you want to retain that space, you may want to write a function that trims the white space in stringAfterNumber.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.