C-Style String Worksheet Answers


  1. char phrase[81];
    


  2. char again[31] = "Emmi Schatz";
    


  3. cout << "Enter your favorite phrase (80 chars max): ";
    cin >> phrase;
    


  4. cout << "You entered: " << phrase << endl;
    


  5. void printstr(char string[])
    {
       int i;
       for (i = 0 ; string[i] != '\0' ; i++)
          cout << string[i];
    }
    


  6. No, because it prints all chars from the beginning of the string until it finds the null byte. The function assumes there is a null byte in the string because that is required for c-style strings.

  7.    int main()
       {
          char line[81];
          cout << "Enter a string\n";
          cin.getline(line,81);
          int i = 0;
          while (line[i] != '\0')
          {
             while (line[i] != ' ' && line[i] != '\t'
                                  && line[i] != '\0')
             {
                cout << line[i];
                i++;
             }
             cout << endl;
             while (line[i] == ' ' || line[i] == '\t')
                i++;
          }
       }
    


  8.    void revstr(char forward[], char backward[])
       {
          int i, j;
          i = strlen(forward) - 1;
          for (j = 0 ; i >= 0 ; j++, i--)
             backward[j] = forward[i];
          backward[j] = '\0';
       }
    




Email Me | Office Hours | My Home Page | Department Home | MCC Home Page

© Copyright Emmi Schatz 2002