logo

UTK Notes


Clicker Questions - 04-More-Strings

(BTW, I'm omitting the "include" and "using" lines to conserve space. Just pretend that the correct ones are there.)

input-1.txt

Dear Earl,
Great Job!
Love Madison

p1.cpp

1
2
3
4
5
6
7
8
9
10
int main()
{
  string s, r;

  while (cin >> s) {
    r += s;
  }
  cout << r.size() << endl;
  return 0;
}
  • Question 1: What is the output of p1.cpp when it runs with input-1.txt as standard input?
Answer

The program reads six strings:

  1. "Dear" -- 4 characters.
  2. "Earl," -- 5 characters (the comma counts).
  3. "Great" -- 5 characters
  4. "Job!" -- 4 characters (the exclamation point counts).
  5. "Love" -- 4 characters
  6. "Madison" -- 7 characters

Thus, r will be the sum of the characters. The answer is 29.

p2.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int main()
{
  string s;
  vector <string> v;
  size_t i;
  int total;

  while (cin >> s) v.push_back(s);
  total = 0;
  for (i = 1; i < v.size(); i++) {
    total += (v[i][0] - v[i-1][0]);
  }
  cout << total << endl;
  return 0;
}
  • Question 2: What is the output of p2.cpp when it runs with input-1.txt as standard input?
Answer

The program reads six strings:

This reads in the same six strings. It then sums up the difference between each adjacent pair of first characters:

  1. ('E' - 'D') = 1.
  2. ('G' - 'E') = 2.
  3. ('J' - 'G') = 3.
  4. ('L' - 'J') = 2.
  5. ('M' - 'L') = 1.

The sum is 9.

input-2.txt

4
5
6
seven
3

p3.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
int main()
{
  int i;
  int total;

  total = 0;
  while (!cin.fail()) {
     cin >> i;
     total++;
  }
  cout << total << endl;
  return 0;
}
  • Question 3: What is the output of p3.cpp when it runs with input-2.txt as standard input?
Answer

Does this question seem familiar? It should -- it's pretty much the same as the eof() question from the last set. cin.fail() doesn't return true until you try to read "seven". Thus, that while loop is exectued four times -- the answer is 4.

Class Stats, PDF Download