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.
#include "AddBuch.h" //class
#include <iostream>
#include <string>
usingnamespace 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>
usingnamespace 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:
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.
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.