C++题目 字符串逆序输出

题目要求:
将一个字符串str的内容颠倒过来,并输出。str的长度不超过100个字符。
输入:
从键盘接收的任意一行字符串。
输出:
转换好的逆序字符串。
示例输入:
I am a student
示例输出:
tneduts a ma I

#include <iostream>

#include <string>

using namespace std;

int main()

{


    string a;

    getline(cin,a);

    string b(a.rbegin(),a.rend());

    cout<<b;


return 0;

}


追问

getline(cin,a);
string b(a.rbegin(),a.rend());
不好意思,以上两句能简单解释下吗。。。不是很懂getline以及迭代器的用法。。C++初学者。。

追答

看下http://www.cplusplus.com/reference/
里面的string api

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2017-09-02
//使用STL实现,四行代码即可,供参考:
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
void main()
{
 string strTmp = "";
 cin >> strTmp;
 reverse(strTmp.begin(), strTmp.end());
 cout << strTmp << endl;
}

追问

当输入的字符串含有空格时,输出不对

追答

因为有空格被cin识别为分割符。

支持空格的代码如下:

#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
void main()
{
 string strTmp = "";
 getline(cin, strTmp, '\n');
 reverse(strTmp.begin(), strTmp.end());
 cout << strTmp << endl;
}

本回答被提问者采纳
第2个回答  2013-10-30
告诉你方法你自己去实现

就是 统计字符串的长度len;
然后第一个字符和最后一个对调
第2个和倒数第2个对调
如果len是奇数那么刚好对调(len-1)/2次
len是偶数就对调len/2次
自己想想就是这么搞 这样算法效率最高 只需要1个临时变量就可以

最快回答这个 其实是一种取巧的做法 没有真正把字符串就地逆置
第3个回答  2013-10-30
#include <string.h>
#include <iostream>

#define  N  100
using namespace std;

int main(int argc,char** argv)
{
char text[N]={0};
cout<<"请输入一字符串:"<<endl;
cin.getline(text,N);
int len=strlen(text);
char* p=text+len;
cout<<"逆序输出为:"<<endl;
while ((p--)!=text)
{
cout<<*p;
}
cout<<endl;
return 0;
}

相似回答