繁体   English   中英

如何在输入流 C++ 中捕获非 ASCII 字符

[英]How to catch non-ASCII characters in input stream C++

我想读取一些用户输入并检查输入中是否有任何不可打印的ASCII 字符,例如“‰”

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

int main()
{
    string password;
    cin >> password;

    for (unsigned char c : password)
    {
        cout << c << endl;
        cout << (int)c << endl;
        if ((int)c < 32 || (int)c > 127)
        {
            printf(" ! Invalid password inserted !\n");
            return 0;
        }
    }

    return 0;
}

这不起作用,因为(int)c for '‰' 返回 37 而实际上是 137。

    unsigned char c = '‰';
    cout << (int)c << endl;

但是,这确实返回了所需的 137。

使用 C++ 标准库中的std::isprint

它的优点是它是可移植的,像((int)c < 32 || (int)c > 127)这样的表达式不是。

请参阅https://en.cppreference.com/w/cpp/string/byte/isprint

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM