fork download
  1. //Sam Partovi CS1A Ch. 10, P.588, #2
  2. /*******************************************************************************
  3. * CREATE REVERSED STRINGS
  4. * ____________________________________________________________
  5. * This program accepts a given string and reverses the order of the characters,
  6. * and displays the contents of the string in reverse order.
  7. * ____________________________________________________________
  8. * INPUT
  9. * ARRAY_SIZE: Size of string array
  10. * string: Given string to reverse
  11. * OUTPUT
  12. * The string variable's contents in reversed order
  13. *******************************************************************************/
  14. #include <iostream>
  15. #include <cstring>
  16. using namespace std;
  17.  
  18. //Function prototype for ReverseStringFunc
  19. char *ReverseStringFunc(char string[]);
  20.  
  21. int main() {
  22.  
  23. const int ARRAY_SIZE = 101; //INPUT - Size of string array
  24. char string[ARRAY_SIZE]; //INPUT - Given string to reverse
  25.  
  26. //Prompt for given string
  27. cout << "Enter a string up to " << ARRAY_SIZE - 1 << " characters: ";
  28. cin.getline(string, ARRAY_SIZE);
  29.  
  30. //Call ReverseStringFunc function and assign returned value to string
  31. ReverseStringFunc(string);
  32.  
  33. //Display the reversed string
  34. cout << "\n" << string;
  35.  
  36. return 0;
  37. }
  38.  
  39. //******************************************************************************
  40. //Function definition for ReverseStringFunc
  41. // This function accepts a given string and returns it in reversed order.
  42. //*****************************************************************************/
  43. char* ReverseStringFunc(char string[]) {
  44. int length = strlen(string); //Obtain string length
  45. char temp; //Temporary variable for swap
  46.  
  47. //Reverse the string
  48. for (int i = 0; i < length / 2; i++) {
  49. temp = string[i];
  50. string[i] = string[length - i - 1];
  51. string[length - i - 1] = temp;
  52. }
  53.  
  54. return string; //Return the reversed string
  55. }
  56.  
Success #stdin #stdout 0s 5288KB
stdin
"Regal as tide", Kramer remarked. "It's a lager!"
stdout
Enter a string up to 100 characters: 
"!regal a s'tI" .dekramer remarK ,"edit sa lageR"