0

Hi,
I am new to c++ and just wanted to know how to split a sting e.g if someone were to enter their details like
John age 19 dob 10/06/1986
into a basic cin, how could I split the string to store John 19 10 06 1986 into different strings or values so I can process them each differently,
thanks!

Just something basic I have so far

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

int main()
{
	string details;
	cout << "Enter Details:\n\n";
             cin >> details;
2
Contributors
2
Replies
3
Views
12 Years
Discussion Span
Last Post by rupz
0

using the >> operator, cin will split up the text for you. In the code you posted, if you display the value of details variable you will see that it only contains the first "word". If you typed "John 19 10 06 1986", details will contain only "John". you will need other variables to store the other words, for example (you should use better variable names than I do in this example -- I don't know what those variables mean)

string name;
int n1,n2,n3,n4;
cin >> name >> n1 >> n2 >> n3 >> n4;

or if you want all of them in "details", use getline()

string detils;
getline(cin, details);

Now, getline will contains all the words. You can use std::string's find method to locate the spaces and use std::string's substr method to extract subsections of the string.

This topic has been dead for over six months. 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.