我是新手,目前正在学习C ++。我目前正在学习cctype(ctype)中的字符函数。我无法理解为什么isspace(a_character)没有返回我的cout消息 - 问题是它甚至不接受我的Char用户输入。任何帮助或指导正确的方向将不胜感激。如果我分配Char值,我可以实现我想要的响应:' '然而,它失败了目的。我复制了部分代码。根据我的理解,空白没有确切的符号?如果是这样,是否可以输入空格作为输入?我尝试过进入:' '但是,没有成功。再一次,我非常感激。
#include <iostream>
#include <cctype>
#include <ctype.h>
using namespace std;
int main()
{
char c ;
char ans = 'y' || 'Y';
do {
cout << "Enter a character \n";
cin >> c;
if (isspace (c)) //Having trouble get this to actually produce a value
{
cout << "Your character " << c << "is a whitespace";
}
if (ispunct(c))
{
cout << c << " is a punctuation character\n";
}
cout << "Would you like to enter another value? \n";
cin >> ans;
} while (ans == 'Y' || ans == 'y');
return 0;
}
答案 0 :(得分:5)
>>
是格式化的提取器。默认情况下,格式化提取器在实际读取任何内容之前提取并丢弃所有空格字符。这是有用的行为,但不是在你试图读取空白字符时。
使用无格式输入(get()
)或noskipws
操纵器。请注意,稍后阅读ans
很可能取决于跳过空白以正常工作,因此您可能希望使用skipws
恢复空白跳过行为如果您选择第二个选项,请在阅读c
之后。