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;
3
  • cin >> str; will receive the 1st word of your input only. Commented Jul 19, 2017 at 21:38
  • Possible duplicate of stackoverflow.com/questions/236129/… Commented Jul 19, 2017 at 21:40
  • Have you tried cin >> str_1 >> str_2 >> str_3 >> str_4 >> str_5;? Commented Jul 19, 2017 at 21:43

2 Answers 2

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;
Sign up to request clarification or add additional context in comments.

1 Comment

Hi, if using the third method, is there a way to tell the compiler how long each split string should be?
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.