简体   繁体   English

C++|将用户输入存储到模板变量

[英]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;首先声明C obj; basically makes no sense, as C is a template class.基本上没有意义,因为C是一个模板类。 As an example, this would be like declaring std::vector vec;例如,这就像声明std::vector vec; instead of std::vector<int> vec;而不是std::vector<int> vec; . . But apart from that, std::cin will not put whatever input it gets into whatever variable it gets.但除此之外, std::cin不会将它获得的任何输入放入它获得的任何变量中。 You would need to get the input into a string, then parse it.您需要将输入转换为字符串,然后对其进行解析。 For this, I suggest making a separate singleton that overloads operator>>() .为此,我建议制作一个单独的单例来重载operator>>()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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