上传新文件

上级 10f258a3
//left.cpp -- string function with a default argument
#include <iostream>
const int Arsize = 80;
char* left(const char* str, int n = 1);
int main(void)
{
using namespace std;
char sample[Arsize];
cout << "Enter a string:\n";
cin.get(sample, Arsize);
char* ps = left(sample, 4);
cout << ps << endl;
delete[]ps; //free old string
ps = left(sample);
cout << ps << endl;
delete[]ps; //free new string
return 0;
}
char* left(const char* str, int n)
{
if (n < 0)
{
n = 0;
}
char* p = new char[n + 1];
int i;
for ( i = 0; i < n && str[i]; i++)
{
p[i] = str[i]; //copy characters
}
while (i <= n)
{
p[i++] = '\0'; //set rest of string to'\0'
}
return p;
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册