C ++ split line

I am trying to split a string using spaces as a separator. I would like to store each token in an array or vector.

I tried.

    string tempInput;
    cin >> tempInput;
    string input[5];

    stringstream ss(tempInput); // Insert the string into a stream
    int i=0;
    while (ss >> tempInput){
        input[i] = tempInput;
        i++;
    }

The problem is that if I type "this is a test", the array seems to save the input [0] = "this". It does not contain values ​​for input [2] through input [4].

I also tried using a vector, but with the same result.

+4
source share
3 answers

Go to recurring questions to learn how to break a string into words, but your method is really correct. The real problem is how you read the input before trying to separate it:

string tempInput;
cin >> tempInput; // !!!

cin >> tempInput, , . , stringstream :

std::string tempInput;
std::vector< std::string > tokens;
while ( std::cin >> tempInput ) {
   tokens.push_back( tempInput );
}
// alternatively, including algorithm and iterator headers:
std::vector< std::string > tokens;
std::copy( std::istream_iterator<std::string>( std::cin ),
           std::istream_iterator<std::string>(),
           std::back_inserter(tokens) );

. , getline <string> cin >> tempInput:

std::string tempInput;
while ( getline( std::cin, tempInput ) ) { // read line
   // tokenize the line, possibly with your own code or 
   // any answer in the 'duplicate' question
}
+5

, copy:

vector<string> tokens;
copy(istream_iterator<string>(cin),
     istream_iterator<string>(),
     back_inserter(tokens));

, : tempInput. . , cin, not . stringstream .

+3

The easiest way: Boost.Tokenizer

std::vector<std::string> tokens;

std::string s = "This is,  a test";
boost::tokenizer<> tok(s);
for(boost::tokenizer<>::iterator it=tok.begin(); it != tok.end(); ++it)
{
  tokens.push_back(*it);
}

// tokens is ["This", "is", "a", "test"]

You can only parameterize separators and escape sequences for spaces, if you want, by default it symbolizes both spaces and punctuation marks.

+1
source

Source: https://habr.com/ru/post/1743133/


All Articles