DEV C++ has a few questions about CIN

1. To use cin, you need to add

using namespace std;

Also need to add header files:

#include <iostream>

2. How to prevent errors in the input content and how to clear the buffer:

#include <iostream>
#include <math.h>
//#include <ipmapip>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
long b,c;
long  d;
using namespace std;

int main(int argc, char** argv) {
	b=8;
	c=3;
	d=(b+c);
	d=pow(d,c);
//	printf("%d",d);
//	cout<<d<<endl;
//	cout<<d+d<<endl;
//	cin>>d;
//	cout<<d<<endl;
	while(c!=9999)
		{
			cout<<"Please enter a number: ";
		//	c=0;
		//		fflush(stdin);
		cin.clear(); //Clear the contents of the input buffer to avoid errors
		cin.sync();
		
		/*
		
		cin.clear() is used to change the status identifier of cin. When cin receives wrong input, it will set the status bit good. If the good bit is not 1,
		Then cin does not accept input and skips it directly. If the status bit does not change before the next input, the input cannot be input even if the buffer stream is cleared.
		So cin.clear() must be done before clearing the buffer.


		cin.ignore(a, ch): Extract characters from the input buffer, the extracted characters are ignored and not used. Every time a character is discarded, it counts and compares the characters,
		If the count reaches a or the ignored character is ch, the cin.ignore() function terminates execution. The default parameter is a=1, i.e. only the first character in the buffer is ignored.
		One of its common functions is to clear the contents of the input buffer that ends with a carriage return, eliminating the influence of the previous input on the next input. For example cin.ignore(1024, '\n'),
		Usually the first parameter is set large enough so that in fact only the second parameter always works, so this sentence is to clear all characters before the carriage return (including the carriage return) from the input buffer.


		The role of cin.sync() is to clear the entire contents of the input buffer.
		
		*/
		
			cin>>c;
	//	cin.get( c);
		if (cin.fail()==0){
		 
		
			cout<<"The number you entered is: "<< c <<endl;
		} else
		{
			cout<<"You have entered illegal content!"<<endl;
		 }
		}
	return 0;
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324606463&siteId=291194637