Skip to content

Back to module

Files


Q) Consider the following code:

C++
int sum = 0; 
println("Enter numbers to add up; negative to exit: ");
while (true) {
    int value = 0;
    cin >> value;
    if (value < 0) {
        XXXXXXXXX
    } 
    sum += value;
}
println("Sum is: {}", sum);

Which of the following should replace the line XXXXXXXXX in order for the program to print the sum of a bunch of positive numbers entered by the user (ending when the user enters a negative number)?

a) return;
b) break;
c) exit(EXIT_SUCCESS);
d) exit(EXIT_FAILURE);


Q) What is the purpose of the following function?

C++
vector<int> baz(string fileName)
{
    vector<int> data;
    ifstream inFile(fileName);

    string line;
    while (getline(inFile, line)) {
        int val = stoi(line);
        if (val > 0) {
            data.push_back(val);
        }
    }
    return data;
}

Assume that fileName is the name of a file containing integers.

a) Returns a vector of all the values from the file.
b) Returns a vector of the first values in the file.
c) Returns a vector of all positive numbers in the file. d) Returns a vector of all lines of text in the file.


Answers

b) break;
d) Returns a vector of all the positive numbers in the file.