-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleft.cpp
More file actions
38 lines (35 loc) · 733 Bytes
/
left.cpp
File metadata and controls
38 lines (35 loc) · 733 Bytes
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
// left.cpp -- string function with a default argument
#include <iostream>
const int ArSize = 80;
char * left (const char * str, int n = 1);
int main()
{
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;
ps = left(sample);
cout << ps << endl;
delete [] ps;
return 0;
}
// this function return a pointer to a new string
// consisting of the first n characters in the str string
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';
}
return p;
}