C++作业: 输入一字符串,反向输出每一个字符,并求此字符串的长度。

如题所述

#include<iostream>
using namespace std;
/* 反向输出字符串,返回字符串长度*/
int reverse(char* str)
{
int n = 0;
while(*(str + n))
{
n++;
}
for(int i = n - 1; i >= 0; i--)
{
cout<<*(str + i);
}
return n;
}
int main()
{
cout<<"输入一段字符串:"<<endl;
char str[256] = {0};
cin>>str;
cout<<"反向输出字符为:"<<endl;
int len = reverse(str);
cout<<endl<<"输入的字符串长度为:"<<len<<endl;
return 0;
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-05-02
一会功夫就回答了这么多啊,那我就给楼主用一种新的方法实现下吧,说实话我也是第一次用vector ,楼主的问题让我学习会了vector,值了,不采纳没关系,只要楼主学到知识就行。

#include<iostream>
#include<vector>
//#include<stdio.h> //经测试可以不要
using namespace std;
void main()
{
vector<char>str;
char a;
int b=-1;
cout<<"请输入字符串"<<endl;
while((a=getchar())!='\n') /*注意不能写成 while(a=getchar()!='\n') 这个错误害我找了很久啊。。。*/
{
str.push_back(a);
b++;
}

cout<<"反向输出字符串"<<endl;
do
{
cout<<str[b];
b--;
}while(b!=-1);
cout<<'\n';

}

参考资料:小磊客栈

第2个回答  2011-05-04
#include<iostream>
#include<stack>
using namespace std;
stack<char> sts;
void main()
{
char i,temp;
for(i=65;i<70;i++)
{
sts.push(i);//进栈
cout<<i<<" ";
}
cout<<endl;
for(i=65;i<70;i++)
{
temp=sts.top();//取栈顶元素
sts.pop();//出栈
cout<<temp<<" ";
}
cout<<endl;
}
另外,站长团上有产品团购,便宜有保证
第3个回答  2011-05-02
#include<iostream>
using namespace std;
void main()
{

char m[50],n;
int i=0;
while(cin>>n)
{
m[i]=n;
i++;
}
for(int j=i-1;j>=0;j--)
{cout<<m[j];}
cout<<endl;
cout<<"字符个数:"<<i<<endl;
}
第4个回答  2011-05-02
#include <iostream>
using namespace std;
int main()
{
char str[100];
int length;
int i;
cout<<"input a string:"<<endl;
cin>>str;

i = 0;
while(str[i])
{
i++;
}
length = i;
i--;

cout<<"Output:"<<endl;
while(i>-1)
{
cout<<str[i];
i--;
}
cout<<"\n\nstring length is "<<length<<endl;
return 0;
}
相似回答
大家正在搜