i want to read characters from the console and print them one after another only if they have a certain value.
Well i tried using something like this:
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
}
But this doesn’t work as it prints all the characters, so any ideas what should i use?
Thanks a lot!
Edit
Well i want to make polynomial calculator in which the user inputs the terms until pressed Enter, but if for example the user inputs ‘r’ or ‘R’ it will reset the input or ‘q’ and ‘Q’ to quit the program and also even if the user inputs illegall characters like ‘@’,’,’,’;’, etc (also i don’t want ‘r’ or ‘q’ printed) it won’t print them on screen.
Also here’s the printable function:
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
);
}
You may want to change your cout statement to
cout << "You just typed: " << c;That way you can actually see if you’ve hit the if condition successfully. Also post printable().
Here is a sample of just grabbing a char, not sure why you are using getch() you should use cin.get, but anyhow for your example:
For anyone wondering, getch() is available in
conio.h. In my case I am just checking the int representation of the character and if it is > 65 returning true else false.EDIT
Vlad the reason why w and z both show up is their decimal representation of w is 119 and z is 123. Now your isPrintable function has an if condition which allows for this:
This will evaluate to TRUE so if you do not want a w you need to restrict that range.