15.13. Multiple Choice ExercisesΒΆ

We want to open a file and parse its data into our program. What library do we need to include?

The code below reads data from a file called input.txt. What is wrong with the following code?

#include <iostream>
#include <fstream>
using namespace std;

int main() {
  string input;
  string filename = "input.txt";
  ifstream infile(filename.c_str());
  getline(filename, input);
}

We want to make sure the file we wanted to open was opened successfully. Which of the following checks this and prints the proper output?

Which of the following statements are true?

What are the contents of the output file output.txt after running the code below?

#include <iostream>
#include <fstream>
using namespace std;

int main() {
  ofstream outfile("output.txt");

  if (!outfile.good()) {
    cout << "Unable to open file" << endl;
  }

  cout << "Powers of 2: ";
  outfile << "2 4 8 16 32 64" << endl;
}

The file scores.txt contains data about the roster number and test scores of students in a class. The output file averages.txt should store each student's roster number and average test score. What should replace the question marks?

#include <iostream>
#include <fstream>
using namespace std;

int main() {
  string junk;
  int studentNum;
  double mid1, mid2, final;
  ifstream infile("scores.txt");
  ofstream outfile("averages.txt");

  if (!infile.good() || !outfile.good()) {
    cout << "Unable to open a file" << endl;
  }

  getline(infile, junk);
  outfile << "Student#\tAverage" << endl;

  while (infile >> studentNum >> mid1 >> mid2 >> final) {
    double avg = (mid1 + mid2 + final) / 3;
    ???
  }
}

What does the following code do?

#include <iostream>
#include <string>
using namespace std;

int main() {
  string original = "430-0444";
  string digitString = "";

  for (size_t i = 0; i < original.length(); i++) {
    if (isdigit(original[original.length() - 1 - i])) {
      digitString += original[original.length() - 1 - i];
    }
  }
  cout << atoi(digitString.c_str()) << endl;
}

Which of the following statements are false about the Set data structure?

There are many ways to construct a matrix. Which of the following are valid constructors of a matrix?

What is the output of the following code?

#include <iostream>
#include <vector>
using namespace std;

bool secret_function(int num) {
  if (num % 2 == 0) {
    return true;
  }
  return false;
}

int main() {
  matrix<int> mat(4, 2);
  for (size_t i = 0 i < mat.size(); ++i) {
    for (size_t j = 0; j < mat[i].size(); ++j) {
      if (!secret_function(i + j) {
        mat[i][j] = 0;
      }
      else {
        mat[i][j] = i + j;
      }
    }
  }
  int n;
  for (size_t i = 0 i < mat.size(); ++i) {
    for (size_t j = 0; j < mat[i].size(); ++j) {
      n += mat[i][j];
    }
  }
  cout << n << endl;
}