1
0

left.cpp 896 B

1234567891011121314151617181920212223242526272829303132333435
  1. // left.cpp -- string function with a default argument
  2. #include <iostream>
  3. const int ArSize = 80;
  4. char * left(const char * str, int n = 1);
  5. int main()
  6. {
  7. using namespace std;
  8. char sample[ArSize];
  9. cout << "Enter a string:\n";
  10. cin.get(sample,ArSize);
  11. char *ps = left(sample, 4);
  12. cout << ps << endl;
  13. delete [] ps; // free old string
  14. ps = left(sample);
  15. cout << ps << endl;
  16. delete [] ps; // free new string
  17. // cin.get();
  18. // cin.get();
  19. return 0;
  20. }
  21. // This function returns a pointer to a new string
  22. // consisting of the first n characters in the str string.
  23. char * left(const char * str, int n)
  24. {
  25. if(n < 0)
  26. n = 0;
  27. char * p = new char[n+1];
  28. int i;
  29. for (i = 0; i < n && str[i]; i++)
  30. p[i] = str[i]; // copy characters
  31. while (i <= n)
  32. p[i++] = '\0'; // set rest of string to '\0'
  33. return p;
  34. }