扫描字符串的ASCII值
问题描述:
我想检查一个字符串是否包含除0-9或A-Z以外的任何字符,如果是,请停止程序。这是我所做的:扫描字符串的ASCII值
string number_in;
for (int i = 0; number_in[i] == '\0'; i++)
{
if ((number_in[i] < 48) || ((number_in[i] > 57) && (number_in[i] < 65)) || (number_in[i] > 90))
{
cout << "\nInput number contains incorrect characters!\n";
getchar;
return 0;
}
}
但无论我输入哪个字符串,它总是跳过for循环。为什么?
答
number_in[i] == '\0'
应该是number_in[i] != '\0'
。 for循环在条件为真时运行。
答
number_in[i] == '\0'
似乎是不正确的。这是继续运行的循环条件。
但是,使用std::isalnum
和std::all_of
一个简单的解决方案:
bool stopProgramm = !std::all_of(std::begin(str), std::end(str),
[] (unsigned char c)
{ return std::isdigit(c) || std::isupper(c); });
答
你应该这样做:
#include <cctype>
// ...
char const c = number_in[i];
if (!(isascii(c) && (isdigit(c) || isupper(c)))) {
// ...
}
严格地说,不需要isascii(c)
,但是,如果你想成为跨平台,如果c
不是ASCII,则其他is*()
函数在Windows上中断。
更改您的号码:'(number_in [i] 2014-11-21 20:52:25
您需要将输入数据更改为所有'\ 0',因此*循环会继续*,因为您告诉编译器在* number [i]等于'\ 0'时使循环*继续。 – 2014-11-21 20:54:28