0

So, I've made this code, and it basically splits up the users input into different strings.

For example

Workspace.Hello.Hey would then be printed out as "Workspace" "Hello" "Hey"

However, I need to know how to define each of those as their own SEPARATE variable that can be called later on. This is the code I have.

std::string str;
    std::cin >> str;
    std::size_t pos = 0, tmp;
    while ((tmp = str.find('.', pos)) != std::string::npos) {
        str[tmp] = '\0';
        std::cout << "Getting " << str.substr(pos) << " then ";
        pos = tmp;
    }
    std::cout << "Getting " << str.substr(pos) << " then ";
J Doe
  • 39
  • 5

3 Answers3

2

C++ has a vectors object in which you can store them in successive indices and access them as you need.

Thinking again on what you're doing, it may be easier to instead feed the string into a stringstream, set . as a delimiter, and then read the contents into a vector of strings as above.

Untitled123
  • 1,317
  • 7
  • 20
  • 2
    See [this post](http://stackoverflow.com/questions/11719538/how-to-use-stringstream-to-separate-comma-separated-strings) – Alec Dec 28 '15 at 02:41
1

Put the substrings in a vector. Here's an example:

std::string str;
std::cin >> str;
std::size_t pos = 0, tmp;
std::vector<std::string> values;
while ((tmp = str.find('.', pos)) != std::string::npos) {
    values.push_back(str.substr(pos, tmp - pos));
    pos = tmp + 1;
}
values.push_back(str.substr(pos, std::string::npos));

for (pos = 0; pos < values.length(); ++pos)
{
    std::cout << "String part " << pos << " is " << values[pos] << std::endl;
}
Alec
  • 583
  • 3
  • 21
  • This solution has an error in the second argument to `tmp`, which should be a `pos`-relative count not an absolute offset. That spawned another question and fixed code's available [here](http://stackoverflow.com/a/34488505/410767). – Tony Delroy Dec 29 '15 at 07:33
0

You can use Boost to tokenize and split the strings. This approach has the added benefit of allowing you to split on multiple delimeters. (see below):

#include <iostream>
#include <string>
#include <vector>
#include <boost/algorithm/string.hpp>
using namespace std;
using namespace boost;

int main() {
    string text = "Workspace.Hello.Hey";

    vector<string> parts;
    split(parts, text, is_any_of("."));

    for(auto &part : parts) {
        cout << part << " ";
    }
    cout << endl;

    return 0;
}
ChrisD
  • 674
  • 6
  • 15