isdigit()c ++,可能是简单的问题,但卡住了 [英] isdigit() c++, probably simple question, but stuck

查看:196
本文介绍了isdigit()c ++,可能是简单的问题,但卡住了的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用isdigit时遇到问题。我读了文档,但是当我cout< isdigit(9),我得到一个0.我不应该得到1吗?

I'm having trouble with isdigit. I read the documentation, but when I cout << isdigit(9), I get a 0. Shouldn't I get a 1?

#include <iostream>
#include <cctype>
#include "Point.h"

int main()
{
    std::cout << isdigit(9) << isdigit(1.2) << isdigit('c');
    // create <int>i and <double>j Points
    Point<int> i(5, 4);
    Point<double> *j = new Point<double> (5.2, 3.3);

    // display i and j
    std::cout << "Point i (5, 4): " << i << '\n';
    std::cout << "Point j (5.2, 3.3): " << *j << '\n';

    // Note: need to use explicit declaration for classes
    Point<int> k;
    std::cout << "Enter Point data (e.g. number, enter, number, enter): " << '\n' 
        << "If data is valid for point, will print out new point. If not, will not "
        << "print out anything.";
    std::cin >> k;
    std::cout << k;

    delete j;
}


推荐答案

isdigit()用于测试字符是否为数字字符。

isdigit() is for testing whether a character is a digit character.

在ASCII字符集(您可能使用它)中, ,9表示水平制表符,不是数字。

In the ASCII character set (which you are likely using), 9 represents the horizontal tab, which is not a digit.

由于您使用I / O流进行输入,您不需要使用 isdigit()验证输入。如果从流读取的数据无效,则提取(即 std :: cin>> k )将失败,因此如果您期望读取int并且用户输入asdf,则提取将失败。

Since you are using the I/O streams for input, you don't need to use isdigit() to validate the input. The extraction (i.e., the std::cin >> k) will fail if the data read from the stream is not valid, so if you are expecting to read an int and the user enters "asdf" then the extraction will fail.

如果提取失败,则将设置流上的失败位。您可以测试此错误并处理错误:

If the extraction fails, then the fail bit on the stream will be set. You can test for this and handle the error:

std::cin >> k;
if (std::cin)
{ 
    // extraction succeeded; use the k
}
else
{
    // extraction failed; do error handling
}

请注意,提取本身也会返回流,缩短前两行是简单的:

Note that the extraction itself also returns the stream, so you can shorten the first two lines to be simply:

if (std::cin >> k)

,结果将是相同的。

这篇关于isdigit()c ++,可能是简单的问题,但卡住了的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆