c++ - isdigit() c++,可能是简单的问题,但卡住了

标签 c++

我在使用 isdigit 时遇到了问题。我阅读了文档,但是当我 cout << isdigit(9) 时,我得到了 0。我不应该得到 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('9'),它将返回非零值。

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


由于您使用 I/O 流进行输入,因此无需使用 isdigit() 来验证输入。如果从流中读取的数据无效,则提取(即 std::cin >> k)将失败,因此如果您希望读取一个 int 并且用户输入“asdf”那么提取就会失败。

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

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

请注意,提取本身也会返回流,因此您可以将前两行简化为:

if (std::cin >> k)

结果是一样的。

关于c++ - isdigit() c++,可能是简单的问题,但卡住了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2970607/

相关文章:

c++ - 赋值运算符与复制构造函数 C++

c++ - 如何在 std::map 中找到所有具有最大值 C++ 的键?

c++ - 在 C++ 中,关于位移和转换数据类型

c++ - Delphi与C++dll通信(参数)

c++ - '\n' 和 std::endl 有什么区别

c++ - 从 VS19 在 Linux 远程计算机上生成 CMake 不起作用

c++ - 我应该如何编写正确的 COM 代码?

c++ - 具有重复键的快速排序算法

c++ - 我不明白为什么我的 .find 函数不起作用

C++ - 加载数据文件失败!