Files¶
Q) Consider the following code:¶
In [ ]:
int sum = 0;
cout << "Enter numbers to add up; negative to exit: ";
while (true) {
int value = 0;
cin >> value;
if (value < 0) {
XXXXXXXXX
}
sum += value;
}
cout << "Sum is: " << sum << endl;
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?¶
In [ ]:
vector<int> baz(string fileName)
{
vector<int> data;
ifstream inFile(fileName);
while (!inFile.fail()) {
int val = 0;
inFile >> val;
if (!inFile.fail() && val > 0) {
data.push_back(val);
}
}
inFile.close();
return data;
}
Assume that fileName
is set to the name of a file containing integers.
a) Returns a vector of all the values from the file.
b) Returns a vector of all the values in the file, if those values are in sorted order (ascending).
c) Creates a file of all the positive values found in its vector
d) Returns a vector of all the positive numbers in the file.
Answers¶
b) break;
d) Returns a vector of all the positive numbers in the file.
In [ ]: