浮点数据意外地成功将 istream 输入为整数
Floating point data unexpectedly succeeds on istream input into an integer
我正在编写一个模板函数,该函数将检查用户是否分配了答案应该包含的正确数据类型。例如:
int main(){
int E;
cout<<"Enter an integer: "<<endl;
E = clear_and_read<int>(cin);
cout<<E<<endl;
}
其中函数clear_and_read
定义为:
template <class T> T clear_and_read(istream& inputstream){
cin.sync();//removes anything still in cin stream
cin.clear();
T input;
inputstream>>input;
while(inputstream.fail()){
cout<<endl<<"Please ensure you are inputting correct data type. Suggested data type: "<< typeid(input).name() <<"."<<endl;
cin.sync();
cin.clear();
inputstream>>input;
}
return input;
}
现在,如果我尝试输入string
而不是integer
,这就可以工作,但是当我输入double
时,它只是分配它的第一个值。 例如 5.678 变为 5。
我可以在模板函数中做什么来标记double
是否正在读入int
?
我会尝试与你略有不同的方法。具体来说,我不会尝试修改输入流的错误状态:
// Untested
template <class T> T clear_and_read(istream& inputstream) {
std::string inputString;
while(1) {
try {
// Grab one maximally-sized whitespace-delimited chunk of input
inputstream >> inputString;
// Note: lexical_cast throws if there are any extraneous characters.
return boost::lexical_cast<T>(inputString);
} catch (boost::bad_cast&) {
std::cout << "nPlease ensure you are inputting correct data type. Suggested data type: "<< typeid(input).name() <<".n";
}
}
}
<小时 />注意:如果您的编译环境中没有可用的 boost,那么自己实现lexical_cast
是相当简单的。如果您遇到困难,请寻求帮助。
<小时 />引用:
- http://www.boost.org/doc/libs/1_49_0/doc/html/boost_lexical_cast.html
<小时 />编辑这是一个经过全面测试的版本,不依赖于Boost。
#include <exception>
#include <sstream>
#include <string>
#include <iostream>
#include <typeinfo>
template <class T> T clear_and_read(std::istream& inputstream) {
std::string inputString;
while(inputstream) {
// Grab one maximally-sized whitespace-delimited chunk of input
inputstream >> inputString;
std::istringstream itemstream(inputString);
// Convert it:
T t;
itemstream >> t;
// See if conversion worked and consumed everything
if(itemstream && (itemstream.get() == EOF)) {
// SUCCESS
return t;
}
// oops
std::cout << "nPlease ensure you are inputting correct data type. Suggested data type: "<< typeid(T).name() <<".n";
}
std::cout << "What to do with EOF?n";
return T();
}
int main () {
clear_and_read<int>(std::cin);
clear_and_read<double>(std::cin);
}
您必须检查输入流的整个输入是否已被消耗。 运算符>>每当遇到第一个非数字时都会停止转换为整数。同样,"3.14qwe"将转换为 3.14 双倍。
相关文章:
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 2D数组来自文本输入,中间有空格
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 检查输入是否不是整数或数字
- 如何使 std::istream 从键盘获取输入(如 std::cin)?
- 此功能希望从std :: istream解析该功能的输入格式
- 如何使用ISTream对象输入多个字符到对象的数组中?(and 0作为哨兵值.下面的我的代码将无效)
- C 从IStream指定输入并测试
- 从输入文件中读取c ,具有iStream Operator Overloading
- C++集合对象和 iStream 文件输入
- istream用于C++/Poco的命令行输入
- 用C++过滤istream中的非法输入
- 如何在iStream&Operator中输入字符串
- 从 istream 输入中一次读取一个字符
- 如何将二进制十六进制文字输入 std::istream
- 浮点数据意外地成功将 istream 输入为整数
- 为什么我什至会在检查有效输入时使用 istream::ignore
- 方便地将 std::vector<unsigned char> 复制到输入流 (std::istream) 对象
- 如何通过用户在键盘上输入初始化istream
- C++ iStream 运算符>>期望任意输入类型