使用指针作为参数,编写函数求字符串的长度。在主函数输入字符串并输出其长度。
#include<iostream>
using namespace std;
int length(char *p);
int main()
{
int len;
char str[20];
cout<<"Please enter a string:";
cin>>str;
cout<<endl;
len=length(str); //调用函数
cout<<"The length of string is:"<<" "<<len<<endl;
}
int length(char *p) //定义求字符串长度的函数
{
int n=0;
while(*p!='\0') //字符串以'\0'结尾
{
n++; //长度+1
p++; //字符串中下一个字母
}
return n;
}