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掉的吗?求正确答案。

转载于:https://www.cnblogs.com/a2htray/p/4141785.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值