在c++中向后打印
Print backwards in c++
这是一个程序,我输入一个句子并向后打印…
#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循环不会为你赢得任何编程比赛。
相关文章:
- 如何循环打印顶点结构
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 如何在c++中打印目录
- 有一个打印语句的函数是一种糟糕的编程实践吗
- 在线编译器中的分段C++没有打印消息
- 在C++中打印指向不同基元数据类型的指针的内存地址
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 如何将结构插入到集合中并打印集合的成员
- 在循环C++中指定字符串之后,不会打印该字符串
- 以螺旋方式打印矩阵的程序.(工作不好)
- 从控制台中删除最后打印的元素
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 如何仅使用对象名称打印特定于对象的成员
- 回溯C++不打印函数,因此文件
- 在一定长度后从数组中打印时缺少整数
- 为什么这个 c++ 代码打印出长度 5,当我打印出字符串时,程序会自动终止?
- 在gem5中打印文件中的所有cache_blocks
- 打印数字图案
- Log4cpp:以UTC/GMT时区打印日期
- 如何使用gdb制作一个可以漂亮地打印每个对象的C++函数