我想从控制台读取字符,只有当它们具有特定值时才一个接一个地打印它们。
好吧,我试过使用这样的东西:
char c;
while (c != '\n') {
c = getch();
if (printable(c)) cout << c; // where printable is a function which checks
// if the character is of a certain value
}
但这不起作用,因为它会打印所有字符,所以我应该使用什么想法?
非常感谢!
编辑
好吧,我想制作多项式计算器,用户在其中输入项直到按下 Enter,但是如果例如用户输入“r”或“R”,它将重置输入或“q”和“Q”以退出该程序,即使用户输入非法字符,如“@”、“、”、“;”等(我也不想打印“r”或“q”),它也不会在屏幕上打印它们。
还有一个可打印的函数:
bool printable(char c)
{
return (
((int(c) > 42 && int(c) < 123) || isspace(c)) && int(c) != 44 && int(c) != 46 && int(c) != 47 &&
int(c) != 58 && int(c) != 59 &&
int(c) != 60 && int(c) != 61 && int(c) != 62 && int(c) != 63 && int(c) != 64 && int(c) != 65 &&
int(c) != 91 && int(c) != 92 && int(c) != 93 && int(c) != 95 && int(c) != 96
);
}
最佳答案
您可能希望将 cout 语句更改为 cout << "You just typed: " << c;
这样你就可以真正看到你是否成功地达到了 if 条件。同时发布 printable()。
这里是一个只抓取一个字符的示例,不确定你为什么使用 getch() 你应该使用 cin.get,但无论如何对于你的示例:
bool isPrintable(char c)
{
bool isItPrintable=false;
if ((int)c >= 65)
isItPrintable=true;
return isItPrintable;
}
int main()
{
char c;
while (c != '\r')
{
c=getch();
if (isPrintable(c))
{
cout << "You just entered: " << c << endl;
}
}
return 0;
}
对于任何想知道的人,getch() 在 conio.h
中可用。 .在我的例子中,我只是检查字符的 int 表示,如果它大于 65,则返回 true,否则返回 false。
编辑
Vlad w 和 z 都出现的原因是 w 的十进制表示是 119 而 z 是 123。现在你的 isPrintable 函数有一个允许这样做的 if 条件:
(int(c) > 42 && int(c) < 123)
这将评估为 TRUE,因此如果您不想要 w,则需要限制该范围。
关于c++ - 帮助 C++ 中的字符输入和打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2411098/