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.

Recommended Answers

All 2 Replies

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;
  cin.get();
  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.

Worked perfectly, thank you :D!!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.