[英]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 '‰'我想读取一些用户输入并检查输入中是否有任何不可打印的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;
}
This does not work, because (int)c
for '‰' returns 37 when it is actually 137.这不起作用,因为
(int)c
for '‰' 返回 37 而实际上是 137。
unsigned char c = '‰';
cout << (int)c << endl;
This, however, does return the desired 137.但是,这确实返回了所需的 137。
Use std::isprint
from the C++ standard library.使用 C++ 标准库中的
std::isprint
。
It has the advantage that it's portable, expressions like ((int)c < 32 || (int)c > 127)
are not.它的优点是它是可移植的,像
((int)c < 32 || (int)c > 127)
这样的表达式不是。
See https://en.cppreference.com/w/cpp/string/byte/isprint请参阅https://en.cppreference.com/w/cpp/string/byte/isprint
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.