【问题标题】:String splitting function skips user input [duplicate]字符串拆分功能跳过用户输入[重复]
【发布时间】:2021-02-04 18:52:59
【问题描述】:

我有一个用空格分割字符串的函数。

代码如下:

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

这应该用空格分割输入,它似乎是这样做的,除了函数一次只返回一个值,并且重复这样做直到输出向量为空:

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:

出于某种原因,它似乎也跳过了输入。我不知道发生了什么,请帮忙!

【问题讨论】:

  • 您的意思是在while 循环中读取输入字符串吗?

标签: c++ string split


【解决方案1】:

operator&gt;&gt; 一次只读取 1 个以空格分隔的单词,因此 main() 中的循环在每次迭代中仅读取 1 个单词并将该单词传递给 split(),因此 split() 没有空格去寻找。

改为使用std::getline() 读取用户的整个输入直到终止Enter,然后您可以根据需要拆分输入。

现在您知道 operator&gt;&gt; 一次只能读取 1 个以空格分隔的单词,您可以利用它来简化您的 split() 函数。

试试这样的:

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

【讨论】: