I am working on a school assignment that's asking me to finish a program that will display a name a given number of times. Everything works fine except for the looping statement that is to repeat the name. Here is the code (note the comments indicating the section that is not functioning correctly:
#include <iostream>
#include <string>
usingnamespace std;
//main PROGRAM
int main()
{
string name;
int limit;
cout << "Please enter the number of times to display your name: ";
cin >> limit;
while (limit < 0)
{
cout << "ERROR: The number you enter must be a number greater than or equal to 0\n";
cout << "Please enter the number of times to display your name: ";
cin >> limit;
}
// Beginning of problem
cout << "Please enter your name: ";
getline(cin, name);
cin.ignore();
for (limit != 0; limit > 1; limit--)
{
cout << name << endl;
}
// End of problem
system("pause");
return 0;
}
I put the cin.ignore() to have it ignore the enter key pressed when entering the value.
Without the cin.ignore(), it just skips to the end of the program.
@moorecm
Where in the code am I mixing them up? If there is a thread that will explain this, please point me to it.
Found the fix for this problem. As moorecm said, the problem is in mixing getline and >> operators. It appears the new line character during the limit input was stuck in the buffer, so it needed to be cleared. Here's the working code with the correction noted in comments for any future reference:
//PRE-PROCESSOR DIRECTIVES
#include <iostream>
#include <string>
usingnamespace std;
//main PROGRAM
int main()
{
string name;
int limit;
cout << "Please enter the number of times to display your name: ";
cin >> limit;
cin.ignore(); // The new line character must be cleared from here
while (limit < 0)
{
cout << "ERROR: The number you enter must be a number greater than or equal to 0\n";
cout << "Please enter the number of times to display your name: ";
cin >> limit;
cin.ignore(); // The new line character must be cleared from here
}
cout << "Please enter your name: ";
getline(cin, name);
for (int i = 1; i <= limit; i++)
{
cout << name << endl;
}
system("pause");
return 0;
}