I am new in C++ template. I want to imitate the Python input()
function to c++
because it is way more cleaner and easy to read and understand but, I have a semantic problem below.
#include <iostream>
#include <string>
using namespace std;
template<class T>
T input(string prompt = ""){
cout<< prompt;
T value;
cin >> value;
return value;
}
int main()
{
// this is the problem
int age = input<int>("Enter your age: "); // try to input a string
cout<< age; // output: 0
}
My question is:
This is working with an
int
input but why is that whenever I input a string, it returns 0?Is there any other way to do this imitation?
Or, how to raise an exception whenever I input non-int?
I wanna know this so that I can handle the error of a user when a user inputs a non-int value in the command line.
Thank You very much.