从使用 sstream 读取的单词中删除最后一个空白 space 的最佳方法?

Best way to remove the last blank space from words read using sstream?

所以,我的代码应该在不改变它们在输入中出现的顺序的情况下打乱句子中的单词。代码工作正常,但在输出的末尾有一个空白 space,这会导致显示错误。

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

using namespace std;

int main() {
    string line;
    while(getline(cin,line)){
        stringstream ss(line);
        string word;
        while(ss>>word){
            string sWord;
            for(int i=word.length()-1;i>=0;i--) {
                sWord+=word.at(i);
            } 
            cout << sWord << " ";
        } 
    cout << endl;
    }
}

这是由 cout << sWord << " "; 行造成的,它打印空白 space 而不管单词的位置。我试图将那部分代码重写为:

cout << sWord;
if(ss>>word) cout << " "; // if there is a following word, print the space; else don't

但是因为我又写了 ss>>word,当下一次迭代开始时,它从第 3 个单词(或第 5 个、第 7 个等)开始,跳过了我不打算跳过的内容。

是否有实现此目的的简单方法?

提前致谢!

您可以使用 bool 来测试您是否显示 第一个 单词,例如:

bool is_first = true; // bool flag to test whether first word or not 
while(ss>>word){
        string sWord;
        for(int i=word.length()-1;i>=0;i--) {
            sWord+=word.at(i);
        }
        if(is_first){ // first word
            cout << sWord;
            is_first = false;
        }
        else{ // not first word
            cout << " " << sWord;
        }
} 

通过这种方式,您可以在每次迭代中有效地打印 " " << sWord;,除了第一次迭代,您不输出 space.

我推销更多的东西是这样的:

while(getline(cin,line))
{
    stringstream ss(line);
    string word;
    if (ss>>word)
    {
        string sWord;
        for(int i=word.length()-1;i>=0;i--) 
        {
            sWord=word.at(i);
        } 
        cout << sWord;
        while(ss>>word)
        {
            for(int i=word.length()-1;i>=0;i--) 
            {
                sWord+=word.at(i);
            } 
            cout << " " << sWord;
        } 
    }
    cout << endl;
}

一个额外的如果,但它只发生一次。代码重复,但它是一个非常小的块。

考虑在实际单词前附加 space:

int main () {
    string line;
    while(getline (cin, line)) {
        stringstream ss (line);
        string word;
        bool first = true;
        while(ss >> word) {
            if(first) {
                first = false; //skip the space for the first word
            } else cout << " ";
            string sWord;
            for(int i = word.length () - 1; i >= 0; i--) {
                sWord += word.at (i);
            }
            cout << sWord;
        }
        cout << endl;
    }
}