0

I've got a function to split a string by spaces.

Here's the code:

vector<string> split(string text) {
    vector<string> output;
    string temp;
    while (text.size() > 0) {
        if (text[0] == ' ') {
            output.push_back(temp);
            temp = "";
            text.erase(0, 1);
        }
        else {
            temp += text[0];
            text.erase(0, 1);
        }
    }
    if (temp.size() > 0) {
        output.push_back(temp);
    }
    return output;
}

int n = 0;

int main()
{
    while (1) {
        cout << "Main has looped" << endl << "Input:";
        string input;
        cin >> input;
        vector<string> out = split(input);
        cout << n << ":" << out[0] << endl;
        n++;
    }
    return 1;
}

This should split input by spaces, and it seems to do that, except the function only returns one value at a time, and does so repeatedly until the output vector is empty:

Main has looped
Input:Split this text
0:Split
Main has looped
Input:1:this
Main has looped
Input:2:text
Main has looped
Input:

It also seems to be skipping the input, for some reason. I have no clue what's happening, please help!

1 Answers1

0

operator>> reads only 1 whitespace-delimited word at a time, so your loop in main() is reading only 1 word on each iteration and passing that word to split(), so there are no spaces for split() to find.

Use std::getline() instead to read the user's whole input up to a terminating Enter, and then you can split the input as needed.

And now that you know operator>> reads only 1 whitespace-delimited word at a time, you can utilize that to simplify your split() function.

Try something more like this:

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

std::vector<std::string> split(const std::string &text) {
    std::vector<std::string> output;
    std::istringstream iss(text);
    std::string word;
    while (iss >> word) {
        output.push_back(word);
    }
    return output;
}

int main()
{
    int n = 0;
    std::string input;

    do {
        std::cout << "Input:";
        if (!std::getline(std::cin, input)) break;
        std::vector<std::string> out = split(input);
        std::cout << n << ":";
        for(size_t idx = 0; idx < out.size(); ++idx) {
            std::cout << out[idx] << " ";
        }
        std::cout << std::endl;
        ++n;
    }
    while (true);

    return 1;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770