how do you use the clear function?

complete

Last edited on
bump
Try the following

#include <limits>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int getInt(int& n)
{
	cout << "\nEnter a number between 1-22: ";
	cin >> n;

	if (cin.fail())
	{
		cin.clear();
		cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
		cout << "error";
		cout << "enter a new integer: ";
		cin >> n;
	}


	
	return 0;
}


EDIT: There was a typo so I updated the code.
Last edited on
I'm still getting the same error
wait i forgot to put include
Last edited on
Im stilling getting the error with include <limits>
There was a typo in my previous post.
It works but the only thing is, we haven't learned #include<limits> yet. And in the example on the website, they don't use it either.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// clearing errors
#include <iostream>     // std::cout
#include <fstream>      // std::fstream

int main () {
  char buffer [80];
  std::fstream myfile;

  myfile.open ("test.txt",std::fstream::in);

  myfile << "test";
  if (myfile.fail())
  {
    std::cout << "Error writing to test.txt\n";
    myfile.clear();
  }

  myfile.getline (buffer,80);
  std::cout << buffer << " successfully read from file.\n";

  return 0;
}
Vlad was error testing the input and the other thing is error testing opening a file. You don't need limits to see if a file opens successfully or not.
In your example there is no need tp call ignore because there is an attempt to write data in a file that was opened for read only mode.
Last edited on
What is this line exactly doing? I've seen the ignore part but the inside stuff is throwing me off. For the cin.fail() to work, do you have to have the ignore with all the stuff or is there an alternate way?

 
cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
The function ignores all characters from the input buffer until it enocunteres the new line character. std::streamsize is a typedef for the integer type of the size of the input buffer. function max returns maximum value for this integer type.
alright, i sorta understand it. I guess if that's the only way to do it, I'll just do it that way.
You can put a large number where the limit is if its too hard to use or you don't want to use limits. As vlad already mentioned it is just the numeric limit for the stream which would mean you ignore everything in the stream you can also ignore a set amount of characters if you would like.
cin.ignore( 1024 , '\n' ); I wouldn't recommend it though I would just use std::numeric_limits
Well it isn't a matter of which way is better, it's just that i haven't learned limits yet in my class so i dont know if the teacher would want us using them.
Topic archived. No new replies allowed.