-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathleftover.cpp
60 lines (54 loc) · 940 Bytes
/
leftover.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// leftover.cpp -- overloading the left() function
#include <iostream>
unsigned long left(unsigned long num, unsigned ct);
char * left (const char * str, int n = 1);
int main()
{
using namespace std;
const char * trip = "Hawaii!!!";
unsigned long n = 12345678;
int i;
char * temp;
for (int i = 1; i < 10; i++) {
cout << left(n, i) << endl;
temp = left(trip, i);
cout << temp << endl;
delete [] temp;
}
return 0;
}
unsigned long left(unsigned long num, unsigned ct)
{
unsigned digits = 1;
unsigned long n = num;
if (ct == 0 || num == 0) {
return 0;
}
while (n /= 10) {
digits++;
}
if (digits > ct) {
ct = digits - ct;
while (ct--) {
num /= 10;
}
return num;
} else {
return num;
}
}
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];
}
while (i <= n) {
p[i++] = '\0';
}
return p;
}