关于字符串倒置的问题

hikui 2009-06-06 09:52:43
我的问题是这样的:
现在我需要倒置字符串,这个字符串既有中文,又有英文,又有空格,而且长度在输入之前未知,现在将其倒置。

#include<iostream>
#include <algorithm>
using namespace std;
int main()
{
string a;
cin>>a;
reverse(a.begin(),a.end());
for(int i=0;i<=a.size();i++)
if(a[i]<0)
{swap(a[i],a[i+1]);i++;}
cout<<a<<endl;
system("pause");
return 0;
}

这样写的话解决倒置中英文混合字符串,但是遇到空格就over了。由于长度未知,我不能使用cin.getline。那么我要怎么办才好呢?
...全文
24 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
GoonYangXiaofang 2009-06-06
  • 打赏
  • 举报
回复
getline;

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

int main()
{
string s;

while (getline(cin, s))
{
reverse(s.begin(), s.end());
for (int i = 0; i <= s.size(); ++i)
{
if (s[i] < 0)
{
char temp = s[i];
s[i] = s[i+1];
s[i+1] = temp;
++i;
}
}
cout << s << endl;
}

return 0;
}



[Quote=引用 1 楼 adventurelw 的回复:]
我晕
string是用getline(cin, a)来读取行啊。
[/Quote]
lingyin55 2009-06-06
  • 打赏
  • 举报
回复
#include <iostream>
#include <string>
using namespace std;

void main()
{
string str = "abcdef";
string::reverse_iterator iter;

for( iter = str.rbegin(); iter != str.rend(); ++iter )
{
cout << *iter;
}

}
hikui 2009-06-06
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 adventurelw 的回复:]
我晕
string是用getline(cin, a)来读取行啊。
[/Quote]
好吧,似乎不是。。。。。
对于string类我基本上是不懂的,我们上课还没学这些诶。。。
抱歉哦,我刚刚开始学。。。
adventurelw 2009-06-06
  • 打赏
  • 举报
回复
我晕
string是用getline(cin, a)来读取行啊。

65,206

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧