【问题标题】:Preventing the console from entering whitespace (i.e. space, tab, and newline) in the ch character (in c++)防止控制台在 ch 字符中输入空格(即空格、制表符和换行符)(在 C++ 中)
【发布时间】: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 &gt;= 'a' &amp;&amp; ch &lt;= 'z')) || (!(ch &gt;= 'A' &amp;&amp; ch &lt;= 'Z')) 将始终为真,因为没有字符是小写的,而它们是大写的。
  • 此外,即使输入在开始时有效,代码也会显示“无效输入”,因为您使用的是do-while循环。
  • 另外,您的do-while 声明无效,因为'Z')); 之间缺少一个)
  • 这并没有解决问题,但有字符编码(EBCDIC 之一)将非字母字符粘贴在值范围内 ['a' .. 'z'] 和值范围内 @987654330 @,所以ch &gt;= 'a' &amp;&amp; ch &lt;= 'z' 对于非小写字符可以为真。使用std::islowerstd::isupper 来测试大小写,或std::isalpha 来检查字母字符。

标签: c++ character user-input whitespace removing-whitespace


【解决方案1】:

cin &gt;&gt; ch; 将跳过空白字符,因此只需删除 do-while 部分。

Demo:

#include <iostream>
using std::cin;
using std::cout;

int main(){
    char ch;
    cout << "Enter the character: ";
    cin >> ch;
    cout << (int)ch << '\n';
    return 0;
}

输入:

 a

输出:

Enter the character: 97

可以看到a之前的空白字符被跳过了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-17
    • 1970-01-01
    • 2011-04-04
    • 1970-01-01
    • 1970-01-01
    • 2011-03-14
    • 1970-01-01
    • 2018-10-15
    相关资源
    最近更新 更多