I’m trying to write a function to detect separators as defined by an assignment and I know it is not good programming style to
#define EXCLAMATION_POINT 33, but to instead do #define EXCLAMATION_POINT '!'
This is my code:
#include <iostream>
#include <ostream>
using namespace std;
#define PERIOD '.'
#define QUESTION_MARK '?'
#define EXCLAMATION_POINT '!'
#define COMMA ','
#define COLON ':'
#define SEMICOLON ';'
inline bool IsSeparator(int x)
{
if (isspace(x) ||
x == PERIOD ||
x == QUESTION_MARK ||
x == EXCLAMATION_POINT ||
x == COMMA ||
x == COLON ||
x == SEMICOLON) {
return true;
}
else {
return false;
}
}
int main (int argc, char * const argv[]) {
int input;
cout << "Enter characters: \n";
input = cin.get();
if (!IsSeparator(input))
cout << "true";
else {
cout << "false";
}
return 0;
}
But in my IsSeparator(), how do I typecast that int to a char to be compared to ‘!’. I thought if I did something like (char)EXCLAMATION_POINT that would work, but it does not and the value is left at an int. What am I doing wrong here? Thanks!
You don’t need any cast, but:
should be:
Also, your prompt:
implies you can enter multiple characters. So you can, but cin.get() will only read one.
Regarding giving symbolic names to things. Suppose you are parsing a file where the separator is a colon. It then makes sense to say:
because you can then change it when the file format changes, for example to:
but it doesn’t normally make sense to give your own names to the members of the ASCII (or whatever) character set.
In your code, it might make sense to create an array of separators (I’m not showing all the ones you use for my ease of typing):
and then have your validation function iterate over the array. Note in this case, the array could also have been expressed as a string literal: