-1

I have a code that gets a string of numbers that is separated by whitespace like: "19 210 67"

And separates them and prints them out. But the thing is I want to put three them into an array one by one so I have an array of strings like: ["19","210","67"]

How can I achieve that? Thanks.

Heres my C++ code:

    std::string s = myText;
    std::string delimiter = " ";

    size_t pos = 0;
    std::string token;
    while ((pos = s.find(delimiter)) != std::string::npos) {
        token = s.substr(0, pos);
        std::cout << token << std::endl;
        s.erase(0, pos + delimiter.length());
    }
    std::cout << s << std::endl;
YKerem
  • 82
  • 10

3 Answers3

2

Use std::istringstream to parse the string, and std::vector<std::string> to store each individual string:

#include <string>
#include <vector>
#include <sstream>
#include <iostream>

int main()
{
    std::string test = "19 210 67";
    std::istringstream strm(test);
    std::vector<std::string> vec;
    std::string s;

    // loop for each string and add to the vector
    while ( strm >> s )
       vec.push_back(s);

    // Output the results
    for (auto& v : vec)
      std::cout << v << " ";
}

Output:

19 210 67 
PaulMcKenzie
  • 34,698
  • 4
  • 24
  • 45
2

Try boost split (found in #include <boost/algorithm/string.hpp> ), here is an example with tab delimiters:

    string input("hello world"); 
    vector<string> result; 
    boost::split(result, input, ' '); 

Alternative just declare a vector and push_back the tokens in the for loop of your code?

user3684792
  • 2,542
  • 2
  • 18
  • 23
-1

Let's assume you have an arbitrary number of values, and they all int First, you tokenize your string:

How do I tokenize a string in C++?

the result of tokenization is a sequence of (std::string or null-terminated char* string) tokens, which you need to transform. This will look something like:

std::transform(
    token_iterator_at_first_token,
    token_iterator_after_last_token,
    [](const auto& token) { return std::stoi(token); }
);

... depending on how your iterators look. If you got a container, the iterators will probably be refered to as the_container.cbegin() and the_container.cend().

einpoklum
  • 118,144
  • 57
  • 340
  • 684