0

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:

  1. This is working with an int input but why is that whenever I input a string, it returns 0?

  2. Is there any other way to do this imitation?

  3. 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.

Eric Echemane
  • 94
  • 1
  • 9
  • 1
    Take a look at how [operator>>](https://en.cppreference.com/w/cpp/io/basic_istream/operator_gtgt) works. When you call `input`, no matter what you enter, it'll try to store the results as an `int`. In the case of non-numeric string data, `0` is written to `value` and eventually returned. You can check that an extraction has failed by checking `cin.fail()` after performing `cin >> value`. – Nathan Pierson Nov 29 '20 at 15:59
  • Thank you. Now I can throw an exception if a user fails to input an int... – Eric Echemane Nov 29 '20 at 16:05
  • `if (cin.fail()) throw "int is expected. non-int is entered.\n";` This line doesn't throw the message: instead: terminate called after throwing an instance of 'char const*' – Eric Echemane Nov 29 '20 at 16:09
  • 1
    A C-style string literal isn't a valid exception object to throw. Try `throw std::runtime_error("Unable to convert argument to the correct type");` or something similar. `"int is expected"` isn't even an accurate error message for the templated version of the function, it's only valid for `input` specifically. – Nathan Pierson Nov 29 '20 at 17:29

0 Answers0