1

im trying to get a user input: "aa bb cc dd ee" etc. which is stored in a single string and put it in multiple strings string_1 "aa", string_2 "bb", string_3 "cc", string_4 "dd", string_5 "ee" etc.

string str;
cin >> str; //user input

//code to split the string

string str_1, str_2, str_3, str_4, str_5;
Cpp plus 1
  • 990
  • 8
  • 25
jelle66
  • 15
  • 1
  • 5

2 Answers2

3

The std::istream& operator>>(std::istream&, std::string) already does that splitting for you. Inputs are separated from whitespaces.

So writing

std::string str_1, str_2, str_3, str_4, str_5;
std::cin >> str_1 >> str_2 >> str_3 >> str_4 >> str_5;

will do what you want to achieve.


If you really need to have the input stored into a single string 1st, you should use the std::getline() function:

std::string str;
std::getline(std::cin,str);

and use a std::istringstream to split up the individual values:

std::istringstream iss(str);
iss >> str_1 >> str_2 >> str_3 >> str_4 >> str_5;
user0042
  • 7,917
  • 3
  • 24
  • 39
  • Hi, if using the third method, is there a way to tell the compiler how long each split string should be? – Madmint Sep 30 '20 at 21:13
2
#include <stringstream>

int main()
{
    std::string MasterString = "Super cali\nfragelistic \n expialadogis\n then more words\n hello world";
    std::stringstream iss(MasterString);

    while(iss.good())
    {
        std::string SingleLine;
        getline(iss,SingleLine,'\n');
        // Process SingleLine here
    }
}

something like this.

Saubhagya
  • 155
  • 12