这是一个程序,我输入一个句子并向后打印......
#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 . . .
正如你所看到的,蜜蜂与蜜蜂之间没有空间。鸟类,那么如何在那里添加空间呢?
答案 0 :(得分:1)
最干净,最简单的解决方案是依靠标准库:
答案 1 :(得分:0)
您可以使用({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;
}
答案 2 :(得分:0)
到达原始输入行的末尾时添加空格:
if printIt == scrambleWords.length()-1
cout << " ";
在
之后将此代码放在内部for循环中if (isspace(scrambleWords[printIt]))
break;
请注意,打破for循环不会赢得任何编程选美比赛。