fork download
  1. //Zachary Abdollah CS1A Chapter 10, P. 588, #2
  2. //
  3. /*******************************************************************************
  4. *
  5. * DISPLAY BACKWARD STRING
  6. *_______________________________________________________________________________
  7. * This program accepts a C-string from the user and passes a
  8. * pointer to the C-string to a function that displays its
  9. * contents backward.
  10. *_______________________________________________________________________________
  11. * INPUT
  12. * userString : C-string entered by the user
  13. *
  14. * OUTPUT
  15. * None (the reversed C-string is displayed directly to the screen)
  16. *
  17. *******************************************************************************/
  18.  
  19. #include <iostream>
  20. #include <cstring>
  21. using namespace std;
  22.  
  23. // Function Prototype
  24. void displayBackward(const char *strPtr);
  25.  
  26. int main ()
  27. {
  28. const int SIZE = 100; // Maximum C-string size
  29. char userString[SIZE]; //INPUT
  30.  
  31. // Input String
  32. cout << "Enter a string: ";
  33. cin.getline(userString, SIZE);
  34.  
  35. // Output Result
  36. cout << "The string backward is: ";
  37. displayBackward(userString);
  38. cout << endl;
  39.  
  40. return 0;
  41. }
  42.  
  43. /*******************************************************************************
  44. *
  45. * FUNCTION displayBackward
  46. *_______________________________________________________________________________
  47. * This function accepts a pointer to a C-string and displays
  48. * its characters in reverse order from the last character
  49. * before the null terminator back to index 0.
  50. *_______________________________________________________________________________
  51. * INPUT
  52. * strPtr : Pointer to a null-terminated C-string
  53. *
  54. * OUTPUT
  55. * None (displays characters directly to console)
  56. *
  57. *******************************************************************************/
  58. void displayBackward(const char *strPtr)
  59. {
  60. int length = strlen(strPtr); // Length of the C-string
  61.  
  62. for (int index = length - 1; index >= 0; index--)
  63. {
  64. cout << *(strPtr + index);
  65. }
  66. }
Success #stdin #stdout 0s 544KB
stdin
Gravity
stdout
Enter a string: The string backward is: ytivarG