用于处理不同类型输入的模板

时间:2018-04-16 07:31:40

标签: c++ c++11 templates

我正在撰写this SO帖子,用于阅读任何类型的用户输入。 我在下面写了模板。但是,当给出字符串输入代替字符时,问题开始,或者给出浮点数代替整数。当浮点数作为整数的输入时,只有小数点前的数据被赋给变量。例如:当我们将6.7分配给整数时,分配6,但.7留在输入缓冲区中。在不等待用户输入的情况下自动分配给下一个字符。我们该如何处理?除非输入缓冲区中有东西要清除,否则我无法调用public class NotificationListener extends NotificationListenerService { @Override public void onCreate() { super.onCreate(); } @Override public void onNotificationPosted(StatusBarNotification sbn) { otherActivity.loc(); } @Override public void onNotificationRemoved(StatusBarNotification sbn) { Log.i("Msg","Notification Removed"); } 。输入正确数据时调用std::cin.clear()会导致无限期等待某个字符。

std::cin.clear()

Output is here

EDIT2: 查看回复后,更新下面的模板功能。能够处理浮点或整数。但我无法处理示例模板函数中的字符和字符串。我绝对可以选择超载功能,但我猜这会失败。

#include <iostream>
#include <limits>
using namespace std;

template <typename myType>
void getInput(myType &data, const string& promptMessage)
{
    std::cout<<promptMessage;
    std::cin>>data;
    while(std::cin.fail())
    {
        std::cin.clear();
        cin.ignore(std::numeric_limits<int>::max(),'\n');
        cout<<"Entered Invalid data, Re-Enter: \n";
        std::cin>>data;
    }

}

void getInput(string &data, const string& promptMessage)
{
    std::cout<<promptMessage;
    getline(std::cin,data);
}

int main(void)
{
    int myInt;
    //cout<<"Enter an Integer : ";
    getInput(myInt, "Enter the Integer Data: ");
    cout<<"Integer Value read = "<<myInt<<endl;

    char myChar;
    getInput(myChar, "Enter single Character: ");
    cout<<"Character read = "<<myChar<<endl;
    return(0);
}

输出在这里。 output for Edit2

1 个答案:

答案 0 :(得分:1)

  

当我们将6.7分配给整数时,分配6,但.7留在输入缓冲区

>>读取一个整数,并在下一个字符不能是整数的一部分时停止。所述字符可以是空格字符,换行符或小数点字符。 >>并不关心,它不会假设您希望如何处理它。也许在输入一个整数后,你需要输入一个字符,然后输入另一个整数。或者一个字符串。 &#39; 0.7&#39;在任何一种情况下都是非常好的输入。

如果你想要,例如读取一行并确保整数是该行的唯一内容,您需要自己做这些事情:

  1. 读一行
  2. 从行
  3. 中提取整数
  4. 验证除了可能的空格外没有别的东西
  5. 处理此类输入的一种方法是:

    template <typename myType>
    void getInput(myType &data, const std::string& promptMessage)
    {
        std::cout<<promptMessage;
        std::string line;
        std::getline(std::cin, line);
    
        if (!std::cin)
            throw std::runtime_error("End of file or IO error");
    
        std::stringstream ss(line);
    
        while (!(ss >> data) || !(ss >> std::ws) || !ss.eof())
        {
            std::cout<<"Entered Invalid data, Re-Enter: ";
            std::getline(std::cin, line);
            std::stringstream ss2(line);
            std::swap(ss, ss2);
        }
    }
    

    如果您需要对char进行专门处理(例如,您不想跳过空白区域),那么char的功能就会超载std::string