简体   繁体   中英

C++|Storing user input to template variables

I want somehow to remove all restrictions from input, what I mean:

int x;
cin >> x;

this allows the user to "answer" only with an integer, if the user writes a string as an input, either nothing or errors happen, if the "answer" is a float or double the number will be converted to int and data will be lost. I want to solve that problem, I remembered templates that allow you to do functions more generic you do not need to care that much about data types, so I thought that I could use that to input and make input more generic, freer, but it does not work even if I make the function that does the input a method.

The code:

#include <iostream>

template <class T>
class C {
    public:
    T x;
    void f(){
        std::cin >> x;
    }
};
int main(int argc, char *argv[])
{
    C obj;
    obj.f();
    return 0;
}

The error:

error: use of class template 'C' requires template arguments
        C obj;
        ^
<stdin>:4:7: note: template is declared here
class C {

If you know or you can imagine something please consider answering to my question, anything as long as it gives the results I want, the knowledge I seek its considered a solution (if possible not too long in lines of code && not too complicated)

First of all, the declaration C obj; basically makes no sense, as C is a template class. As an example, this would be like declaring std::vector vec; instead of std::vector<int> vec; . But apart from that, std::cin will not put whatever input it gets into whatever variable it gets. You would need to get the input into a string, then parse it. For this, I suggest making a separate singleton that overloads operator>>() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM