在C++空间中将字符串分隔成不同的字符串

在C++空间中将字符串分隔成不同的字符串,c++,C++,我接受字符串输入,我需要从一行中读入多个单词,并将它们放入向量中。无论何时只要有空格字符,我都不知道如何分割字符串。我知道我需要使用getline函数,但是我觉得我已经尝试了所有的方法,我被卡住了 这是到目前为止我的代码。我知道if/else语句都在做相同的事情 int main(){ vector<string> vec; string str = ""; string t = ""; int i = 0;

我接受字符串输入,我需要从一行中读入多个单词,并将它们放入向量中。无论何时只要有空格字符,我都不知道如何分割字符串。我知道我需要使用getline函数,但是我觉得我已经尝试了所有的方法,我被卡住了

这是到目前为止我的代码。我知道if/else语句都在做相同的事情

int main(){
    vector<string> vec;
    string str = "";
    string t = "";
    int i = 0;

    while(getline(cin, str){
        if(str != "STOP"){
            if(str[i] == ' '){
                vec.push_back(str);
            }else{
                vec.push_back(str);
            }
        }else{
            cout << vec.size() << endl;
        }
        i += 1;
    }
}
我不能真正使用任何花哨的代码,只使用基本函数

您可以使用getline获取输入,然后使用stringstream分割字符串。比如:

#include <sstream>
#include <vector>
#include <iostream>
using namespace std;

int main(){
    string arr;
    getline(cin, arr);

    stringstream ss(arr);
    string word;

    vector<string> v;
     
    while(ss >> word){
       // your desired strings are in `word` one by one, you can store these strings in a vector
       v.push_back(word);
    }
}
要持续进行输入和处理,请执行以下操作:

#include <sstream>
#include <vector>
#include <iostream>
using namespace std;

int main(){
    string arr;
    
    while(getline(cin, arr)){
    
        stringstream ss(arr);
        string word;
    
        vector<string> v;
         
        while(ss >> word){
           // your desired strings are in `word` one by one, you can store these strings in a vector
           //v.push_back(word);
           cout << word << " ";
        }
        cout << "\n";
    }
}

C++中的字符串分割?LOL。可能是标准库尚未提供的最受欢迎的功能。这个问题是一个重复的,如果你有一个C++20兼容的编译器,你可以使用,这取决于范围库。在用户告诉它停止之前,是否可以使用这种方法,同时不断地输入数据?@Ethah是的,这是可能的,我在回答中也添加了这一部分,看一看谢谢!