识别C 程序中的空间字符

Recognizing Space character in C++ Program

本文关键字:空间 字符 程序 识别      更新时间:2023-10-16
#include<iostream.h>
#include<conio.h>
void main()
{
char ch;
cout<<"Enter a character:";
cin>>ch;
if(ch==32)
cout<<"space";
else if(ch>=65 && ch<=90)
cout<<"upper case letter";
else if(ch>=97 && ch<=122)
cout<<"lower case letter";
else
cout<<"special character entered";
getch();
} 

我需要检查输入的字符是下案字母,特殊字符,数字或空间字符。32是空间的代码,但是当我进入控制台上的空间时,它不识别为空间。

默认空间被忽略,使用 noskipws

#include<iostream>
using namespace std;
int main()
{
char ch;
cout<<"Enter a character:";
cin>>noskipws>>ch;
if(ch==32)
cout<<"space";
else if(ch>=65 && ch<=90)
cout<<"upper case letter";
else if(ch>=97 && ch<=122)
cout<<"lower case letter";
else
cout<<"special character entered";
getchar();
return 0;
} 

另外,如果您将''添加到空间中,请记住只有第一个字符才能识别。

问题

cin >> ch丢弃Whitespaces(包括空间,tn等)正确的方法是使用get(ch)

cin.get(ch);

noskipws是 @samuel的答案中提到的另一个选项,但是在这里,get可能更容易。)

其他问题

  1. 使用<iostream>代替<iostream.h><iostream.h>不是标准C 。
  2. 使用<cstdio> *代替<conio.h><conio.h>不是标准C 。
  3. 使用int main()代替void main()void main()不是标准C 。
  4. 使用凹痕而不是左置。左侧的可读性较低。
  5. 使用ch == ' '代替ch == 32ch == 32无法便携。
  6. 使用isupper(ch)代替ch >= 65 && ch <= 90ch >= 65 && ch <= 90无法便携。
  7. 使用islower(ch)代替ch >= 97 && ch <= 122ch >= 97 && ch <= 122无法便携。

修复代码:

#include <iostream>
#include <cctype>
int main()
{
    char ch;
    std::cout << "Enter a character:";
    std::cin.get(ch);
    if (ch == ' ')
        std::cout << "space";
    else if (std::isupper(ch))
        std::cout << "upper case letter";
    else if (std::islower(ch))
        std::cout << "lower case letter";
    else
        std::cout << "special character entered";
    // std::cin >> ch; // only if you really demand it
}
在这种情况下,

*甚至不应使用<cstdio>。如果您确实想打开窗口,请使用getchar()std::cin >> ch而不是getch()。更好的方法是在控制台中调用它。

使用字符本身而不是代码。

#include<iostream.h>
#include<conio.h>
void main()
{
    char ch;
    cout << "Enter a character:";
    cin >> ch;
    if (ch == ' ')
        cout << "space";
    else if (ch >= 'A' && ch <= 'Z')
        cout << "upper case letter";
    else if(ch >= 'a' && ch <= 'z')
        cout << "lower case letter";
    else
        cout << "special character entered";
    getch();
}