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 ";
1
  • You probably want std::vector<std::string> using push_back to add each string to the vector. Commented Dec 28, 2015 at 2:34

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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;
}

1 Comment

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.
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;
}

2 Comments

Not hugely fond of new libraries when existing features can already do it I am.
@Untitled123 Perhaps, but parsing/splitting a string in C++ can sometimes be a pain without them.

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.