防止C++中的隐式转换

Mar*_*ars 4 c++

我要求用户输入整数,我不想执行代码,除非它是严格的整数.

int x;
if(cin >> x)
Run Code Online (Sandbox Code Playgroud)

例如,如果用户输入上面的double,则if语句将执行,并隐式转换为整数.相反,我根本不希望代码执行.

我怎么能阻止这个?

Pot*_*ter 10

那里没有转换.如果用户输入分数(没有double),则>>提取在小数点处停止.

http://ideone.com/azdOrO

int main() {
    int x;
    std::cin >> x;
    std::cout << std::cin.rdbuf();
}

 input:

123.456

output:

.456
Run Code Online (Sandbox Code Playgroud)

如果要将小数点的存在标记为错误,则必须执行某些操作以从中提取cin并检测它.

使用C++流的一个很好的解析策略是getline你知道你将处理istringstreams,调用它,然后s.peek() == std::char_traits<char>::eof()在你完成时检查它.如果您不使用getline拉取单个数字,则peek可以检查下一个字符是否为空格(使用std::isspace)而不从流中消耗该字符.

可能是检查输入完成的最干净的方法,虽然它有点深奥,但是可以使用std::istream::sentry.

if ( ! ( std::cin >> x ) || std::istream::sentry( std::cin ) ) {
    std::cerr << "Invalid or excessive input.\n";
}
Run Code Online (Sandbox Code Playgroud)

这会在输入结束时占用空间.sentry还提供了noskipws避免占用空间的选项.

if ( ! ( std::cin >> x ) || std::istream::sentry( std::cin, true ) ) {
    std::cerr << "Invalid or excessive input. (No space allowed at end!)\n";
}
Run Code Online (Sandbox Code Playgroud)