【发布时间】:2020-09-01 09:07:07
【问题描述】:
我想阻止控制台在中心代码此处字符(在 c++ 中)输入 空格(即空格、制表符和换行符)。我试过条件 ((!(ch >= 'a' && ch = 'A' && ch 在代码中显示的 do-while 循环中,但它不起作用。如果有人对此有任何了解,请帮助我。
以下是我的代码(c++):
char ch;
cout << "Enter the character: ";
cin >> ch;
do
{
cout << "Invalid input.\n";
cout << "Re-enter the character: ";
cin >> ch;
} while((!(ch >= 'a' && ch <= 'z')) || (!(ch >= 'A' && ch <= 'Z'));
【问题讨论】:
-
(!(ch >= 'a' && ch <= 'z')) || (!(ch >= 'A' && ch <= 'Z'))将始终为真,因为没有字符是小写的,而它们是大写的。 -
此外,即使输入在开始时有效,代码也会显示“无效输入”,因为您使用的是
do-while循环。 -
另外,您的
do-while声明无效,因为'Z'))和;之间缺少一个)。 -
这并没有解决问题,但有字符编码(EBCDIC 之一)将非字母字符粘贴在值范围内
['a' .. 'z']和值范围内 @987654330 @,所以ch >= 'a' && ch <= 'z'对于非小写字符可以为真。使用std::islower和std::isupper来测试大小写,或std::isalpha来检查字母字符。
标签: c++ character user-input whitespace removing-whitespace