How do I clear the buffer?

Hello! This is some code designed to take the first character of a name inputted by the user and wipe the buffer clean to get ready for the next prompt. However, I can't figure out how to use getline or cin.ignore or \n to wipe the buffer. I need to input a name, but it waits until I have exceeded the range in the cin.ignore (20) with inputs. I will input the name, the program returns the first letter, asks for the alphabetical letter, and then wants me to put in the alphabetical letter twice. How do I fix this? Thanks!

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
33
34
35
36
37
#include <iostream>
#include <iomanip> 
#include <string>
#include <cmath>
using namespace std;

int main() 
{
	char userName, userAlpha, userType;
	const int lowMin = 141;
	const int upperMin = 65;

	cout << "Please enter your first name: ";
	cin >> userName;
	cin.ignore(20, ' ');
	cin.get();

	cout << "The first letter is " << userName;

	cout << "Please enter an alphabetical letter: "; 
	cin >> userAlpha;


	if (userAlpha >= 65 || userAlpha <= 90)
	{
		cin >> userType;
		if (userName == userAlpha)
		{
			cout << "You entered an upper case letter! congrats on getting the code to work";
		}
	}


	cout << "You entered " << userAlpha;
	
	return 0;
}

Last edited on
Hello elevona,

The most used way to clear the input buffer is:
1
2
cin >> userName;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');  // <--- Requires header file <limits>. 

This usually follows a "std::cin >>" and is needed before a "std::getline()".
Your use of cin.ignore(20, ' '); will only ignore 20 characters. Therefor if the input buffer has more than 20 characters only the first 20 are ignored.

The "ignore" works by ignoring the number of characters specified by the number or the new line whichever comes first. So if the number is not big enough the buffer will not be cleared.

Quite often I have seen 1000 or 10000 as the first parameter of ignore and this usually works.

The std::numeric_limits<std::streamsize>::max(), is just a way to get the largest number available for the IDE, compiler and operating system you are using.

Hope that helps,

Andy
That does help quite a lot!

Is this the only way to clear the buffer? I'm sorry for asking that of you, but I just know that for this particular assignment, I cannot use anything we haven't gone over, and I am pretty positive we haven't used the header file <limits>.

Hello elevona,

No its not the only way, but worth keeping that line of code for the future.

You can use : std::cin.ignore(1000, '\n'); or 10000. You just need a number large enough to cover what might be in the input buffer.

Andy

Edit:
Last edited on
Hello Andy,

My problem is that the name will vary by user input, and that I grabbed the first character and need to keep that, but clear the rest. Will increasing the number in cin.ignore to 1000 keep the one and clear the others? or will I have to put in 1000 characters to get to the next prompt?

Thanks,

Elevona
Also, I will keep that code for sure! Thank you!
closed account (E0p9LyTq)
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
33
34
35
#include <iostream>
#include <string>
#include <limits>

int main()
{
   std::string userName;
   char userAlpha;
   char userType;

   std::cout << "Please enter your first name: ";
   std::cin >> userName;

   // this wipes the entire input stream, there are no more characters in it
   std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

   std::cout << "The first letter is " << userName.at(0) << "\n\n";

   std::cout << "Please enter an alphabetical letter: ";
   std::cin >> userAlpha;

   // just to play it safe you will want to clear the buffer again since you are reading a single digit
   // and the user might have entered more than one character
   std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

   if (userAlpha >= 65 || userAlpha <= 90)
   {
      if (userName.at(0) == userAlpha)
      {
         std::cout << "You entered an upper case letter! congrats on getting the code to work\n";
      }
   }

   std::cout << "You entered " << userAlpha << '\n';
}
Please enter your first name: Joe
The first letter is J

Please enter an alphabetical letter: J
You entered an upper case letter! congrats on getting the code to work
You entered J
Please enter your first name: Joe D. Ragman
The first letter is J

Please enter an alphabetical letter: t
You entered t
Last edited on

Hello elevona,

Your code
1
2
3
4
5
char userName

cout << "Please enter your first name: ";
cin >> userName;
cin.ignore(20, ' ');

I think what you are not understanding here is that "userName" being defined as a "char" is only one character. "std::cin >> userName;" will only take the first character of the input buffer and store it in "userName" leaving anything left in the input buffer.

So lets say that you type in 25 characters for a name. The first character will be stored in "userName" the next 20 will be ignored leaving four characters in the input buffer.

Increasing the 20 to 50 or 100 or 1000 should solve the problem.

I will load your program and give it a test to see what is happening.

Hope that helps,

Andy
It solved the first portion! However, when prompted for an alphabetical letter, I am required to enter it twice before it shows me the response.


"Please enter your first name: Andy
The first letter is A
Please enter an alphabetical letter: A
///PRogram will not continue until 'A' is entered again
A
You entered an upper case letter!... etc"

Thanks, that helped!!

elevona
closed account (E0p9LyTq)
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
Quite a mouthful, isn't it.

What this is doing is extracting and discarding X number of characters, or until the carriage return ('\n'). If there are less than X characters to extract and discard the buffer will still be emptied and the end-of-file bit will be set.

You can use a number (say 1000) for the maximum number of characters to discard. std::numeric_limits<std::streamsize>::max() indicates there is no limit, discard the maximum number of characters the stream can hold.

You chose a space as a delimiter. The user might enter a string of text that has several spaces in it. "This is a string of text and has a number of spaces" for example. You extract "This" from the input stream, and std::cin.ignore(20, ' '); will find the space right after "This" leaving "is a string of text and has a number of spaces" in the buffer.

Not what you want.
Andy

I'm sorry for trying your patience. I used "std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');" but still encountered the same problem.

I STILL have to enter my response of the alphabetical letter TWICE, though in my code, it doesn't seem to have that. What could be the problem?

Thanks!
closed account (E0p9LyTq)
I am required to enter it twice before it shows me the response.

Ah, that wasn't clear. You didn't mention that earlier, and without a prompt for the user there is no way they can know what to do. Without a prompt it looks like the program just "hung."

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
33
34
35
36
37
38
#include <iostream>
#include <string>
#include <limits>

int main()
{
   std::string userName;
   char userAlpha;
   char userType;

   std::cout << "Please enter your first name: ";
   std::cin >> userName;

   // this wipes the entire input stream, there are no more characters in it
   std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

   std::cout << "The first letter is " << userName.at(0) << "\n\n";

   std::cout << "Please enter an alphabetical letter: ";
   std::cin >> userAlpha;

   // just to play it safe you will want to clear the buffer again since you are reading a single digit
   // and the user might have entered more than one character
   std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

   if (userAlpha >= 65 && userAlpha <= 90)  // need the AND (&&) to check for only alpha characters
   {
      std::cout << "Enter the character again: ";
      std::cin >> userType;

      if (userType == userAlpha)
      {
         std::cout << "You entered an upper case letter! congrats on getting the code to work\n";
      }
   }

   std::cout << "You entered " << userAlpha << '\n';
}
Please enter your first name: Joe
The first letter is J

Please enter an alphabetical letter: A
Enter the character again: a
You entered A
Please enter your first name: Joe
The first letter is J

Please enter an alphabetical letter: B
Enter the character again: B
You entered an upper case letter! congrats on getting the code to work
You entered B
Last edited on
Hello elevona,

After running yur code this is what I cam up with. Note the comments in the code:
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
33
34
35
36
37
#include <iostream>
#include <iomanip> 
//#include <string>  // <--- Neither header file is used.
//#include <cmath>

using namespace std;

int main()
{
	char userName, userAlpha, userType;
	const int lowMin = 141;
	const int upperMin = 65;

	cout << "Please enter your first name: ";
	cin >> userName;
	cin.ignore(20, '\n');
	//cin.get(); // <--- Why is this here. 

	cout << "\nThe first letter is " << userName << std::endl;

	cout << "\nPlease enter an alphabetical letter: ";
	cin >> userAlpha;


	if (userAlpha >= 65 || userAlpha <= 90)
	{
		//cin >> userType;  // <--- What is this for?
		if (userName == userAlpha)
		{
			cout << "\nYou entered an upper case letter! congrats on getting the code to work" << std::endl;
		}
	}

	cout << "\nYou entered " << userAlpha;

	return 0;
}

And produces the output of:

Please enter your first name: Manfred

The first letter is M

Please enter an alphabetical letter: M

You entered an upper case letter! congrats on getting the code to work

You entered M



In your code you have: cin >> userType; // <--- What is this for? this follows cin >> userAlpha;. With out a prompt for cin >> userType; you do not know what you are waiting for and that is why you think you have to enter "A" twice.

As FurryGuy pointed the second parameter of the "ignore" is using a space as the delimiter when it should be '\n'.

Hope that helps,

Andy
“How do I flush input” is a distressingly common question.

The answer is don’t.

The causes of the problems that tend to cause this question have nothing to do with wiping the user’s (valid) input. They are because there is something wrong with the way you are processing it.

You have made a couple of mistakes in understanding here.

The first is that you want to skip all the stuff that the user typed after their first initial, so you thought to use cin.ignore(). (Good job!)

The problem was that you decided to delimit on a space — something the user never input (first name will not likely have a space in it).

So your code, not finding a space, keeps you waiting until 20 inputs are received (which seems random, because you are skipping characters without processing, and on Windows systems, a newline is two characters...).

Then you ask for a single character, which I presume was to rid yourself of the newline.


Remember the cardinal rule of user input:

    The user will always press Enter after every input request.

So, what you should have done is get the first letter, then just ignore everything up to and including the Enter key press that the user gave you.

1
2
3
4
5
  // Skip leading whitespace, get the first letter of the user's name (presumably)
  cin >> ws >> firstNameInitial;

  // Skip all remaining letters (and anything else) until EOL
  cin.ignore( numeric_limits <streamsize> ::max(), '\n' );


Next, watch your logical conditions. If you want to make sure the user input a letter in 'A' .. 'Z', BOTH conditions must hold:

1
2
3
4
5
6
7
8
  if ((userAlpha >= 'A') && (userAlpha <= 'Z'))
  {
    cout << "Good job! You entered the majuscule '" << userAlpha << "'!\n";
  }
  else
  {
    cout << "Hey! That's not what was asked for!\n";
  }

Also, you need to be explicit. The user could have entered a lowercase letter and still been strictly complying with your instructions. Be clear!

1
2
3
4
5
6
  char c;
  cout << "Please enter a letter of the alphabet: ";
  cin >> c;

  if (isalpha( c ))
  ...

If you require the character to be only majusucle, convert it yourself:
 
  c = toupper( c );


I STILL have to enter my response of the alphabetical letter TWICE, though in my code, it doesn't seem to have that. What could be the problem?
The problem is that your code says to ask the user for something twice.

As already noticed, the condition lets any letter through, and then you say cin >> userType;, which makes the program want input — even though you didn’t warn the user that it would be required.


Getting your head around these logical issues takes time.
Don’t get discouraged, you’ll get there soon.

Good luck!
closed account (E0p9LyTq)
I still keep forgetting to skip any possible leading whitespace in the input with these situations. D'OH!
Hello, everyone! I appreciate the very helpful feedback!

Going forward with this, I have solved my issue by feedback from every person who has answered this thread, and I will take all advice given to me. As a beginner AND a woman in computer science, I can get intimidated and discouraged quite often.

Everyone on this thread has been extremely helpful and I am grateful for it.

Thank you, to everyone.

The best,

"elevona"

Only a-holes will give you grief for being a woman in CS.

Unfortunately, there are quite a few of them floating around in CS, so just remember, your worth has nothing to do with what they think.

Also, women have been instrumental in the development of computer science since the very beginning. That’s because women are smart!
Not quite half my peers are female. Women are making huge inroads into STEM and tech fields. at least in the USA.
there is a lot of nonsense about gender and such, but the truth is that there ARE differences. Women and men, when you take it on the average, think a bit differently. Having some female programmers on our team has been nothing but an asset, to get that different approach/point of view on things. When you graduate you will know as much as anyone else, so be confident in your abilities and just do your best, and it will work.
closed account (E0p9LyTq)
Probably the premiere woman in computer science, Rear Admiral (Lower Half) Grace Brewster Murray Hopper.

She is probably the sole person most responsible for creating the idea of programming computers by compiled languages. She practically invented the science of computer science.

You ever get discouraged, remember her.

https://en.wikipedia.org/wiki/Grace_Hopper
Last edited on
Topic archived. No new replies allowed.