Source of ListingC3-5.cpp


  1: //  Created by Frank M. Carrano and Timothy M. Henry.
  2: //  Copyright (c) 2017 Pearson Education, Hoboken, New Jersey.

  4: // Listing C3-5

  6: #include <iostream>
  7: #include <string>

  9: // Encodes the character at index i of the string str.
 10: void encodeChar(int i, std::string& str)
 11: {
 12:    int base = static_cast<int>('a');
 13:    if (isupper(str[i]))
 14:       base = int('A');
 15:    char newChar = (static_cast<int>(str[i]) — base + 3) % 26 + base;
 16:    str.replace(i, 1, 1, newChar); // Method replace can throw exception
 17: } // end encodeChar

 19: // Encodes numChar characters within a string.
 20: void encodeString(int numChar, std::string& str)
 21: {
 22:    for (int j = numChar − 1; j >= 0; j––)
 23:       encodeChar(j, str);
 24: }  // end encodeString

 26: int main()
 27: {
 28:    std::string str1 = "Sarah";
 29:    encodeString(99, str1);
 30:    return 0;
 31: }  // end main