识别C 程序中的空间字符
Recognizing Space character in C++ Program
#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(包括空间,t
,n
等)正确的方法是使用get(ch)
:
cin.get(ch);
(noskipws
是 @samuel的答案中提到的另一个选项,但是在这里,get
可能更容易。)
其他问题
- 使用
<iostream>
代替<iostream.h>
。<iostream.h>
不是标准C 。 - 使用
<cstdio>
*代替<conio.h>
。<conio.h>
不是标准C 。 - 使用
int main()
代替void main()
。void main()
不是标准C 。 - 使用凹痕而不是左置。左侧的可读性较低。
- 使用
ch == ' '
代替ch == 32
。ch == 32
无法便携。 - 使用
isupper(ch)
代替ch >= 65 && ch <= 90
。ch >= 65 && ch <= 90
无法便携。 - 使用
islower(ch)
代替ch >= 97 && ch <= 122
。ch >= 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();
}
相关文章:
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- C++字符*缓冲区的大小
- HEX值到wchar_t字符(UTF-8)的转换
- 命名空间中具有.h和.cpp文件的类
- 为什么 Serial.println(<char[]>);返回随机字符?
- 打印第二列时的2d字符矢量打印空间
- 如何为结构字段动态分配字符空间
- 空间字符函数
- 如何定义一个从任何编码空间解析单个字符的精神 x3 解析器?
- 识别C 程序中的空间字符
- 在线路中的字符之前卸下所有空间
- 是ASCII字符255隐形字符或空间
- 将两次使用的字符放在变量中是空间的增益
- 追加到具有可用空间的字符数组
- 如何将字符串的三个字符放入数组的一个空间中
- 从高效方法中删除指定的字符(时间和空间复杂性)
- 如何从字符变量中删除空白空间
- 是否存在编解码场景,其中目标缓冲区需要多个内部字符的空间
- 将用户输入的空间存储在字符数组中
- 为什么一个字符在数组中似乎比它本身占用更多的空间