leftover.cpp 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // leftover.cpp -- overloading the left() function
  2. #include <iostream>
  3. unsigned long left(unsigned long num, unsigned ct);
  4. char * left(const char * str, int n = 1);
  5. int main()
  6. {
  7. using namespace std;
  8. char * trip = "Hawaii!!"; // test value
  9. unsigned long n = 12345678; // test value
  10. int i;
  11. char * temp;
  12. for (i = 1; i < 10; i++)
  13. {
  14. cout << left(n, i) << endl;
  15. temp = left(trip,i);
  16. cout << temp << endl;
  17. delete [] temp; // point to temporary storage
  18. }
  19. // cin.get();
  20. return 0;
  21. }
  22. // This function returns the first ct digits of the number num.
  23. unsigned long left(unsigned long num, unsigned ct)
  24. {
  25. unsigned digits = 1;
  26. unsigned long n = num;
  27. if (ct == 0 || num == 0)
  28. return 0; // return 0 if no digits
  29. while (n /= 10)
  30. digits++;
  31. if (digits > ct)
  32. {
  33. ct = digits - ct;
  34. while (ct--)
  35. num /= 10;
  36. return num; // return left ct digits
  37. }
  38. else // if ct >= number of digits
  39. return num; // return the whole number
  40. }
  41. // This function returns a pointer to a new string
  42. // consisting of the first n characters in the str string.
  43. char * left(const char * str, int n)
  44. {
  45. if(n < 0)
  46. n = 0;
  47. char * p = new char[n+1];
  48. int i;
  49. for (i = 0; i < n && str[i]; i++)
  50. p[i] = str[i]; // copy characters
  51. while (i <= n)
  52. p[i++] = '\0'; // set rest of string to '\0'
  53. return p;
  54. }