在c++中向后打印

Print backwards in c++

本文关键字:打印 c++      更新时间:2023-10-16

这是一个程序,我输入一个句子并向后打印…

#include<iostream>
#include<string>
using namespace std;
int main(int argc, char* argv[]) {
    string scrambleWords;
    cout << "Please enter a sentence to scramble: ";
    getline(cin, scrambleWords);
    for (int print = scrambleWords.length() - 1; print >= 0; print--)
    {
        if (isspace(scrambleWords[print]))
        {
            for (unsigned int printIt = print + 1; 
                         printIt < scrambleWords.length(); printIt++)
            {
                cout << scrambleWords[printIt];
                if (isspace(scrambleWords[printIt]))
                    break;
            }
        }
    }
    for (unsigned int gotIt = 0; gotIt < scrambleWords.length(); gotIt++)
    {
        cout << scrambleWords[gotIt];
        if (isspace(scrambleWords[gotIt]))
            break;
    }
    cout << endl;
}
// OUTPUT
// Please enter a sentence: birds and bees
// beesand birds
// Press any key to continue . . .

你可以看到蜜蜂之间没有空间&鸟,那么我怎么在这里添加空间呢?

最干净、最简单的解决方案是依赖标准库:

// 1. Get your input string like you did
// 2. Save the sentence as vector of words:
stringstream sentence {scrambleWords};
vector<string> words;
copy(istream_iterator<string>{sentence},istream_iterator<string>{},
    back_inserter(words));
// 3 a) Output the vector in reverse order
for (auto i = words.rbegin(); i != words.rend(); ++i)
    cout << *i << " ";
// 3 b) or reverse the vector, then print it
reverse(words.begin(),words.end());
for (const auto& x : words)
    cout << x << " ";

您可以使用(c++ 11 for auto):(http://ideone.com/mxOCM1)

void print_reverse(std::string s)
{
    std::reverse(s.begin(), s.end());
    for (auto it = s.begin(); it != s.end(); ) {
        auto it2 = std::find(it, s.end(), ' ');
        std::reverse(it, it2);
        it = it2;
        if (it != s.end()) {
            ++it;
        }
    }
    std::cout << s << std::endl;
}

当到达原始输入行末尾时添加一个空格:

if printIt == scrambleWords.length()-1
    cout << " ";

把这段代码放在for循环的内部,在

之后
if (isspace(scrambleWords[printIt]))
    break;

注意跳出for循环不会为你赢得任何编程比赛。