-2

i wrote a code to validate my input

int id;
cout <<"Enter Your ID: "; cin>>id;
    while (cin.fail())
    {
        cout << "\" This is not a valid option please try again: ";
        cin >> id;
        if (cin.fail())
        {
            cin.clear();
            string input;
            cin >> input;
            cout << "\n\t\"" << input << "\" This is not a vaild option please try again: ";
            cin >> id;
        }
    }

so this works but what i want to make a function out of this but the problem is that what data type would i pass in the parameter because the above code could be used for string , ints or chars as well but how do i put that code in a function: is this even possible?

void validation()
{

    while (cin.fail())
    {
        cout << "\" This is not a vaild option please try again: ";
        cin >> id;
        if (cin.fail())
        {
            cin.clear();
            string input;
            cin >> input;
            cout << "\n\t\"" << input << "\" This is not a vaild option please try again: ";
            cin >> id;
        }
    }
}
6563cc10d2
  • 193
  • 1
  • 2
  • 8

1 Answers1

0

Just to get you started here is a very basic example using templates.

#include <iostream>
template<typename InputType>
void validate(InputType input)
{
    std::cout << input << std::endl;
}

int main()
{
    validate(5);

    validate("Hello");

    validate(4.0);
}

Try give it a go, and if you still have problems update your question with your attempt and I will give further assistance.

Tagger5926
  • 442
  • 3
  • 13
  • In your code above, how would you know when a user generated a manual `EOF` with `Ctrl+d`? – David C. Rankin Aug 19 '19 at 00:53
  • The code above is simply an example to show how templates are used. Capturing EOF and ctrl+d signals are entirely different to what the code is supposed to address, which was to make a function generic. If you have a specific question about EOFs then ask it as a separate question sincei t does not directly relate to OP's question. Also, for more reading on EOFs: https://stackoverflow.com/questions/1516122/how-to-capture-controld-signal and https://itstillworks.com/check-ctrld-c-12070026.html – Tagger5926 Aug 19 '19 at 01:21
  • All good, I was just making sure you didn't intend something else. – David C. Rankin Aug 19 '19 at 02:05