#include<iostream>
char *left(const char *ps,int n=1);
int main()
{
using namespace std;
cout<<"输入字符串:";
char ps[100];
cin.get(ps,100);
char *pt=left(ps,3);
cout<<pt<<endl;
delete[] pt;
pt=left(ps);
cout<<pt<<endl;
delete[] pt;
system("pause");
return 0;
}
char *left(const char *ps,int n)
{
using namespace std;
char *p=new char[n+1];
int i;
for(i=0;i<n&&ps[i];i++)
{
p[i]=ps[i];
}
while (i<=n)
{
p[i++]='\0'; //这个地方是i先进行运算,然后在加一,这已经是最后一个了,不明白为什么要再加1呢?
}
return p;
}
char *left(const char *ps,int n=1);
int main()
{
using namespace std;
cout<<"输入字符串:";
char ps[100];
cin.get(ps,100);
char *pt=left(ps,3);
cout<<pt<<endl;
delete[] pt;
pt=left(ps);
cout<<pt<<endl;
delete[] pt;
system("pause");
return 0;
}
char *left(const char *ps,int n)
{
using namespace std;
char *p=new char[n+1];
int i;
for(i=0;i<n&&ps[i];i++)
{
p[i]=ps[i];
}
while (i<=n)
{
p[i++]='\0'; //这个地方是i先进行运算,然后在加一,这已经是最后一个了,不明白为什么要再加1呢?
}
return p;
}