-2

can you please help me, i want to know about clear(), what is its use; what happen if not use this method in this program. I only know about clear() is that, it is used to clear error flags.

#include<iostream>
#include<fstream>
#include<stdio.h>
using namespace std;
void add()
{
    char name[21];
    ofstream k("friends.frn", ios::app);
    cout << "Enter your name : ";
    cin.getline(name, 21);
    cin.clear();
    fflush(stdin);
    k << name;
    k << '\n';
}
int main()
{
    int ch;
    while (1)
    {
        cout << "1. Add"; << endl;
        cout << "2. Exit"; << endl;
        cout << "Enter your choice : ";
        cin >> ch;
        cin.clear();
        fflush(stdin);
        if (ch == 1) add();
        if (ch == 2) break;
    }
    return 0;
}
François Andrieux
  • 28,148
  • 6
  • 56
  • 87
Aman Warudkar
  • 125
  • 1
  • 1
  • 12
  • 2
    Flushing standard input is undefined in both C and C++. –  Oct 24 '17 at 19:51
  • 4
    Duplicate of https://stackoverflow.com/questions/5131647/why-would-we-call-cin-clear-and-cin-ignore-after-reading-input – codeX Oct 24 '17 at 19:51
  • 2
    How about asking [your friend Google](http://www.cplusplus.com/reference/ios/ios/clear/)? – Vivick Oct 24 '17 at 19:52

1 Answers1

1

clear() by itself is not a standard function. It only exists in the standard library as a member function of several standard types. So the behavior of cin.clear() is not the same as other class' clear() method. Each class that implements clear() does so in a way that is rational for that type. For example, std::string::clear() will cause the string to be empty.

See here on cppreference.com for a list of standard clear() member methods.

François Andrieux
  • 28,148
  • 6
  • 56
  • 87