Splitting a String.

--
Last edited on
The simple way would be:
1
2
3
int amount;
string thing;
cin >> amount >> thing;


Since the >> both stops and ignores white space.

Doing it with just a string is a little trickier. You'll want to use find(), and substr()
to figure out where the number ends and to separate the number:
http://www.cplusplus.com/reference/string/string/
And then use atoi to make an integer out of it (requiring the <stdlib.h> header):
http://www.cplusplus.com/reference/clibrary/cstdlib/

Atoi needs a c-string, so also use the string function c_str()
stringstreams are handy for extracting numerics out of strings:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <sstream>
#include <string>

const char *catstring_with_num = "5 cats";
const char *dogstring_with_num = "37 dogs";

int main()
{
  int cats = 0, dogs = 0;
  std::stringstream ss(catstring_with_num);
  ss >> cats;
  ss.str(dogstring_with_num);
  ss >> dogs;
  std::cout << "Got number " << cats << " from string \"" << catstring_with_num << "\"" << std::endl;
  std::cout << "Got number " << dogs << " from string \"" << dogstring_with_num << "\"" << std::endl;
  return 0;
}


Output was:
1
2
3
4
5
Got number 5 from string "5 cats"
Got number 37 from string "37 dogs"

Process returned 0 (0x0)   execution time : 0.016 s
Press any key to continue.

Topic archived. No new replies allowed.