I have a string that I need to split into four variables: cmd1, cmd2, id, address.
I have this:
string x = "ADD ADDRESS 001 21 PARKWAY DRIVE";
string cmd1, cmd2, id, address;
istringstream ss(x);
ss >> cmd1 >> cmd2 >> id >> address;
cout << cmd1 << endl << cmd2 << endl << id << endl << address;
The problem is that if the address input has a space in it, it will only take the input up to the first space, as stringstream does, so how would I get the entire address and store it into "address"?
Looking for this:
INPUT: ADD ADDRESS 001 21 PARKWAY DRIVE
STORED:
cmd1 = ADD
cmd2 = ADDRESS
id = 001
address = 21 PARKWAY DRIVE
Right now, i'm getting this:
INPUT: ADD ADDRESS 001 21 PARKWAY DRIVE
STORED:
cmd1 = ADD
cmd2 = ADDRESS
id = 001
address = 21
Perhaps there is a better method, other than stringstream to split up a string this way?
One way is to read string until id:
ss >> cmd1 >> cmd2 >> id;
and then use getline for address:
getline(ss, address);
also to remove the extra space you can use a string function called substr or use ws:
address = address.substr(1,address.size()); or
ws(ss);
so your program will look like:
#include <iostream>
#include <sstream>
using namespace std;
int main(){
string x = "ADD ADDRESS 001 21 PARKWAY DRIVE";
string cmd1, cmd2, id, address;
istringstream ss(x);
ss >> cmd1 >> cmd2 >> id;
ws(ss);
getline(ss, address);
cout << cmd1 << endl << cmd2 << endl << id << endl << address;
return 0;
}