C++测验代码
1 /* 2 返回字符串前n位和返回整数前n位 3 */ 4 5 #include <iostream> 6 7 unsigned long left(unsigned long num, int n); 8 char * left(char * str, int n); 9 10 using namespace std; 11 12 int main() 13 { 14 unsigned long num; 15 int n; 16 cout << "请输入一个整数:"; 17 cin >> num; 18 cout << "请输入要截取的位数:"; 19 cin >> n; 20 cout << "前" << n << "位为" << left(num, n) << endl; 21 22 char * str = new char(20); 23 cout << "请输入一个字符串:"; 24 cin >> str; 25 cout << "请输入要截取的位数:"; 26 cin >> n; 27 cout << "前" << n << "位为" << left(str, n) << endl; 28 29 //delete[] str; 30 31 cin.get(); 32 cin.get(); 33 } 34 35 36 unsigned long left(unsigned long num, int n) 37 { 38 unsigned long len = 1; //表示这个数一共有几位 39 unsigned long temp_num = num; 40 while (temp_num /= 10) 41 { 42 len++; 43 } 44 unsigned long cut_num_len = len - (unsigned long(n) >= len ? len : unsigned long(n)); //当n小于整数的长度时,直接取回原来的整数 45 while (cut_num_len--) 46 { 47 num /= 10; 48 } 49 return num; 50 } 51 52 char * left(char * str, int n) 53 { 54 int len = strlen(str); 55 n = n >= len ? len : n; 56 char * temp_char = new char(n + 1); 57 58 for (int i = 0; i < n; i++) { 59 *(temp_char + i) = *(str + i); 60 } 61 temp_char[n] = '\0'; 62 return temp_char; 63 }
大家看下,有一个问题,当我取消//delete[] str;注释后,程序会报错,不是鼓励如果是用new自成的指针最好要delete掉的吗?求正确答案。