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;

Recommended Answers

All 2 Replies

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.

thanks a lot, ill give it a try

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.