cin >> n doesn't work

Hi,

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?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
  #include "std_lib_facilities.h"
using namespace 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;
}
doesn't work

In what way does it not work?

isn't behaving itself

What does that mean?


Help us to help you. What does it do that you think it shouldn't, and/or what does it not do that you think it should?
I am sorry, Moschops!

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.
Last edited on
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 

Thank you, Moschops! The program works now! ^_^
Topic archived. No new replies allowed.