Using loop to count number of entries

I'm writing a program that must ask user to type in numbers. After each entry, the program has to report the cumulative sum of the entries to date. The program should terminate when user enters 0.

The code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <string>
int main()
{
	using namespace std;
	char number;
	int count = 0;
cout << "Enter a number: ";
cin.get(number);
		while (number != '0')
		{
			++count;
			cin.get(number);
		};
		cout << "Total of " << count << " inputs.\n";
		system("pause"); // I'm aware that this way is very bad
	return 0;
}


The problem is that if I enter 0, the program will say there's 0 input in total(correct).
If I type in 1 and the next number is 0, program will say there's 2 entries in total.
And if I type in 11 and 0, I get 3 entries in total.
But even more strange is that if you type 111 then 11 then 0 you get total of 7 entries.

No, the program must not show me the sum of all numbers entered, just how many entries you made, untill you typ in 0.
Last edited on
Try a for loop
I think the cin.get leaves carrige return and line feed characters. you should use cin >> instead of cin.get (it is good for reading from file).

about CR and LF:

http://en.wikipedia.org/wiki/Carriage_return
http://en.wikipedia.org/wiki/Newline

about cin.get:
http://www.cplusplus.com/reference/iostream/istream/get/

about cin >>
http://www.cplusplus.com/reference/iostream/istream/operator%3E%3E/
Last edited on
You are reading characters not integers, so spaces will be counted.

should use cin >> instead of cin.get
http://www.cplusplus.com/forum/articles/6046/
Last edited on
Yeh it worked. Thanks.

The code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <string>

int main()
{
	using namespace std;
	int number, count = 0;
cout << "Enter a number: ";
cin >> number;
		for (; number != 0; ++count)
		{
			cin >> number;
		};
		cout << "Total of " << count << " inputs.\n";
		system("pause"); // I'm aware that this way is very bad
	return 0;
}
Topic archived. No new replies allowed.