简体   繁体   中英

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

I want to read some user input and check if there is any non-printable ASCII character in the input, such as '‰'

#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;
}

This does not work, because (int)c for '‰' returns 37 when it is actually 137.

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

This, however, does return the desired 137.

Use std::isprint from the C++ standard library.

It has the advantage that it's portable, expressions like ((int)c < 32 || (int)c > 127) are not.

See https://en.cppreference.com/w/cpp/string/byte/isprint

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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