![]() |
#2
rjsp2018-06-20 08:32
|
编写函数完成字符串反转。要求必须使用C++字符串,必须使用函数
输入
输入有多行,每一行代表一个字符串。 输入行数不确定,以ctrl+z结束。
输出
输出翻转后的字符串。每个字符串占一行。
样例输入
who's your daddy
my daddy is Li Gang
样例输出
yddad ruoy s'ohw
gnaG iL si yddad ym
提示
对于多行判断,可采用while(getline(cin, str))来实现,如果getline获取到ctrl+z,则退出while循环。
于是我写了这样一个代码

#include <iostream>
#include <string>
using namespace std;
string invert(string str,int n)
{
char temp;
for(int i=0;i<n/2;i++)
{
temp=str[i];
str[i]=str[n-1-i];
str[n-1-i]=temp;
}
for(int j=0;j<n;j++)
cout<<str[j];
cout<<endl;
}
int main()
{
string str;
int n;
while(getline(cin,str))
{
n=str.size();
invert(str,n);
}
}
#include <string>
using namespace std;
string invert(string str,int n)
{
char temp;
for(int i=0;i<n/2;i++)
{
temp=str[i];
str[i]=str[n-1-i];
str[n-1-i]=temp;
}
for(int j=0;j<n;j++)
cout<<str[j];
cout<<endl;
}
int main()
{
string str;
int n;
while(getline(cin,str))
{
n=str.size();
invert(str,n);
}
}
问题1 : 输入样例who's my daddy ,下一行确实出现了yddad ruoy s'ohw ,而当我准备输入第二行样例的时候他顿了一下结束了(输入任意键继续那个)
问题2 ; 这个以ctrl+z结束要怎么操作啊
求大佬讲解一下~!蟹蟹~!