-1
#include<iostream>
using namespace std;

class Name
{
     public:
     void tell(string s){cout<<"Your name is "<<s<<endl;}
     void tell(int i){cout<<"Your age is "<<i<<endl;}
};


int main()
{    Name m; string s;
      while(s!="n")
      {
     cout<<"Input your name or age"<<endl;
     cin>> s;

     m.tell(s);
     }

    return 0;
}

The variable 's' should be able to store an int as well as string argument, without losing its type; so that, the 'int' overload gets invoked when I pass an int argument and the 'string' overload gets invoked when I pass a string argument to tell()

1 Answers1

0

"Input your name or age" - well, you at least need to know, what you are about to store, i.e. how to interpret the input value.

If your intent is to detect if the input is a number, you could try to convert to integer, and if that conversion succeeds store the value as int, otherwise as string.

For example with boost::lexical_cast:

#include <boost/lexical_cast.hpp>

cin >> s;
try {
    int age = boost::lexical_cast<int>(s);
    m.tell(age);
} catch (const bad_lexical_cast &) {
    m.tell(s);
}

If you don't have boost, you can try to use different means of conversion, like atoi() (difficult to detect error) or strtol() (possible to detect error) - see also How do I check if a C++ string is an int?.

Community
  • 1
  • 1
EmDroid
  • 5,918
  • 18
  • 18