0

I have this problem while watching tutorials and make one for myself. I can't get a hold of this cin.ignore(). I want the user to type characters only but if he types any integer, it should continue looping until he gets the correct input.

This is my code along with the error mentioned.

#include <iostream>
#include <vector>
#include <climits>
using namespace std;

// simple io validation
int main(){
    char name{};
    char last{};
    int birthday {};
    cout << "Pls Enter your first name: ";
    cin>>name;   // if he type "alfred123 Philip" it should error
    while (!cin.good())  // or while cin.fail()
        {
        cout<<"Please enter character only"<<endl;
        cin.clear();
        cin.ignore(INT_MAX,"/n");  //error no instance of overloaded function "std::basic_istream<_CharT, _Traits>::ignore [with _CharT=char, _Traits=std::char_traits<char>]" matches the argument list
        cout<<"Enter Name: ";   // ask again the user
        cin >> name;

        }
    cout << endl;
    cout<<"Hello "<<name<<endl;
    return 0;
}
risingStark
  • 1,153
  • 10
  • 17
  • `cin.ignore(INT_MAX,'\n');` Note the single quotes and backslash used for an escape character. – Retired Ninja Jul 25 '21 at 06:46
  • 1
    What you're hoping for won't work either, because "abc", "123", and "abc123" are all perfectly valid strings. If you want to disallow numbers you'll need to validate the string after input. `char name{};` is only a single character, not a string. You would want something like `char name[100] = {};` but I'm not sure if formatted input would work then. Is there a reason you're not using `std::string` and making it much simpler? – Retired Ninja Jul 25 '21 at 06:53
  • @Retired Ninja Hello thank you for the answer.. I also wants to question this actually why many programmers used std:: when you can just type namespace std and not worry about it? – Coding is a business Jul 25 '21 at 07:00
  • [Why is “using namespace std;” considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – Retired Ninja Jul 25 '21 at 07:05

0 Answers0