For loop help?

As you my be aware of, I am a beginner in C++ and started using classes. I am asking user how many books he/she would like to enter then used the number provided to ask for that many books. The problem is when I use the for loop it ends up printing the cout message in the loop twice before the user gets the chance to enter.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include "AddBuch.h" //class
#include <iostream>
#include <string>

using namespace std;

int main()
{
	int numMyBuch;
	string nameMyBuch;
	AddBook myBook;

	cout << "How many books do you have to add: ";
	cin >> numMyBuch;
	for (int i = 0; i <= numMyBuch; i)
	{
		myBook.askMsg(numMyBuch, nameMyBuch);
	}
	cin.get();
	cin.get();
	return 0;
}


Then my class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <string>

using namespace std;

class AddBook
{
public:
	void askMsg(int numBuch, string nameBuch)
	{
		cout << "What is the name of your book: \n";
		getline(cin, nameBuch);
	}
};


When I run the program it outputs as:

How many books do you have to add: 5
What is the name of your book: (Two print out at once instead at one at a time.)
What is the name of your book:

Thanks in advance.
Several problems here:

main line 14: After doing the cin >> operation, there is a CR left in the input buffer. Unlike the >> operator, getline does not ignore leading whitespace (including CR). Therefore the CR left over from the >> operation terminates the getline. To avoid this, add cin.ignore (999) after the cin >> operation.

main line 15: The second expression in the for loop should be <, not <=. <= will cause you to execute the loop one extra time.

main line 15: You fail to increment the loop variable. The third expression should be i++

class line 9: You pass nameBuch by value. The value read by getline will be lost when askMsg exits. You want to pass nameBuch by reference so that the caller's variable is updated.


AbstractionAnon,

Thanks SO much! However, just to correct one thing, it should be cin.ignore(); not cin.ignore(999); in this case. Again, thanks for the help!
The default skip value is one so cin.ignore() ignores only a single character. That's fine if the only character left in the input buffer is the CR.

Consider if the user entered 5.123 (silly in this case, but just an example). The ".123" would be left in the input buffer. Therefore a value > 1 would be appropriate.
Topic archived. No new replies allowed.