C++拆分字符串

Mik*_*ike 4 c++ string split

我试图使用空格作为分隔符拆分字符串.我想将每个标记存储在数组或向量中.

我试过了.

    string tempInput;
    cin >> tempInput;
    string input[5];

    stringstream ss(tempInput); // Insert the string into a stream
    int i=0;
    while (ss >> tempInput){
        input[i] = tempInput;
        i++;
    }
Run Code Online (Sandbox Code Playgroud)

问题是,如果我输入"这是一个测试",该数组似乎只存储输入[0] ="这个".它不包含输入[2]到输入[4]的值.

我也试过使用矢量但结果相同.

Dav*_*eas 5

转到重复的问题以了解如何将字符串拆分为单词,但您的方法实际上是正确的.实际问题在于您尝试拆分输入之前如何读取输入:

string tempInput;
cin >> tempInput; // !!!
Run Code Online (Sandbox Code Playgroud)

当您使用时cin >> tempInput,您只能从输入中获取第一个单词,而不是整个文本.有两种可能的方法可以解决这个问题,最简单的方法是忘记stringstream并直接迭代输入:

std::string tempInput;
std::vector< std::string > tokens;
while ( std::cin >> tempInput ) {
   tokens.push_back( tempInput );
}
// alternatively, including algorithm and iterator headers:
std::vector< std::string > tokens;
std::copy( std::istream_iterator<std::string>( std::cin ),
           std::istream_iterator<std::string>(),
           std::back_inserter(tokens) );
Run Code Online (Sandbox Code Playgroud)

这种方法将在单个向量中为您提供输入中的所有标记.如果您需要与各行的工作separatedly那么你应该使用getline<string>头,而不是cin >> tempInput:

std::string tempInput;
while ( getline( std::cin, tempInput ) ) { // read line
   // tokenize the line, possibly with your own code or 
   // any answer in the 'duplicate' question
}
Run Code Online (Sandbox Code Playgroud)