logo

UTK Notes


Clicker Questions - 03-Strings

input-1.txt

aa bb cc dd
ee ff gg hh

p1.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
using namespace std;

int main()
{
  string s1, s2, s3;

  while (cin >> s1 >> s2 >> s3) {
    cout << s1[0] << s2[0] << s3[0];
  }
  cout << endl;
  return 0;
}
  • Question 1: What is the output of p1.cpp when it runs with input-1.txt as standard input?
Answer The first iteration reads "aa", "bb" and "cc". The second iteration reads "dd", "ee", and "ff". The third iteration fails, because there are only two words left. After the words are read, the first character of each word is printed:
abcdef

p2.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <vector>
using namespace std;

int main()
{
  vector <string> sv(3);

  while (cin >> sv[0] >> sv[1] >> sv[2]) {
    cout << sv[0] << sv[1] << sv[2];
  }
  cout << endl;
  return 0;
}
  • Question 2: What is the output of p2.cpp when it runs with input-1.txt as standard input?
Answer The same strings are read as in Question 1, only this time into a vector rather than three separate variables. All of the characters are printed:
aabbccddeeff

input-2.txt

4 5 
3 9

p3.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <vector>
using namespace std;

int main()
{
  int sum, i;

  sum = 0;
  while (!cin.eof()) {
    cin >> i;
    sum += i;
  }
  cout << sum << endl;
  return 0;
}
  • Question 3: What is the output of p3.cpp when it runs with input-2.txt as standard input?
Answer This is a buggy program, because cin.eof() only returns true after it has failed to read the input. So this loop runs five times, and on the last iteration, the (cin >> i) statement fails, leaving i equaling nine. Thus, 9 gets added to the sum twice. The answer is 4 + 5 + 3 + 9 + 9 = 30
30

No Class Stats, PDF Download