/*
返回字符串前n位和返回整数前n位
*/ #include <iostream> unsigned long left(unsigned long num, int n);
char * left(char * str, int n); using namespace std; int main()
{
unsigned long num;
int n;
cout << "请输入一个整数:";
cin >> num;
cout << "请输入要截取的位数:";
cin >> n;
cout << "前" << n << "位为" << left(num, n) << endl; char * str = new char();
cout << "请输入一个字符串:";
cin >> str;
cout << "请输入要截取的位数:";
cin >> n;
cout << "前" << n << "位为" << left(str, n) << endl; //delete[] str; cin.get();
cin.get();
} unsigned long left(unsigned long num, int n)
{
unsigned long len = ; //表示这个数一共有几位
unsigned long temp_num = num;
while (temp_num /= )
{
len++;
}
unsigned long cut_num_len = len - (unsigned long(n) >= len ? len : unsigned long(n)); //当n小于整数的长度时,直接取回原来的整数
while (cut_num_len--)
{
num /= ;
}
return num;
} char * left(char * str, int n)
{
int len = strlen(str);
n = n >= len ? len : n;
char * temp_char = new char(n + ); for (int i = ; i < n; i++) {
*(temp_char + i) = *(str + i);
}
temp_char[n] = '\0';
return temp_char;
}
大家看下,有一个问题,当我取消//delete[] str;注释后,程序会报错,不是鼓励如果是用new自成的指针最好要delete掉的吗?求正确答案。