I am working my way through Bjarne Stroustrup's Programming Principles and Practice Using C++.
An exercise in Chapter 5 asks you to get some numbers from a user, store the numbers in a vector and add the first n numbers. A user decides n. And n is smaller than vector.size().
Here is my code. I don't know why "cin >> n" isn't behaving itself. Can you help?
#include "std_lib_facilities.h"
usingnamespace std;
int main()
try {
cout << "Please enter some numbers: (Press \"|\" to stop): ";
vector <int> num_storage; // Numbers' container.
int i = 0;
while (cin >> i) { // Reads numbers.
num_storage.push_back(i); // Stores numbers.
}
cout << "You have entered " << num_storage.size() << " numbers." << endl;
cout << "Please enter how many of the numbers you wish to sum, starting from the first: ";
int n = 0; // The number a user wants to sum.
if (cin >> n) cout << "n is: " << n << endl;
int sum = 0; // Stores the sum of n integers.
for (int i = 0; i < n; i++) {
sum += num_storage[i];
}
cout << "The sum of " << n << " numbers is " << sum << "." << endl;
return 0;
}
catch (...) {
cerr << "Something went wrong somewhere." << endl;
return 1;
}
Here is the output I receive when I run g++ -std=c++0x ex8.cpp.
1 2 3 4 5 6 7
$ ./a.out
Please enter some numbers: (Press "|" to stop): 1
2
3
|
You have entered 3 numbers.
Please enter how many of the numbers you wish to sum, starting from the first: The sum of 0 numbers is 0.
EDIT:
cin >> n is ignored. It is as if I had commented out the line.
This is related to the bad character | you're using to indicate that the input is finished.
Because extracting it into an int fails, it's just left in the buffer, so that at cin >> n, it's still there and another failed attempt is made to extract it, and because it fails, (cin >> n) is false.
Add the following code at line 12:
1 2
cin.clear(); // clear failure state flags on cin
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // remove everything left in the cin input buffer