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();
i开发者_运维百科f (!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:
if (!IsSeparator(input))
should be:
if (IsSeparator(input))
Also, your prompt:
cout << "Enter characters: \n";
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:
const char SEPARATOR = ':';
because you can then change it when the file format changes, for example to:
const char SEPARATOR = '|';
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):
const char SEPARATORS[] = {':', '|', '!', 0 };
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:
const char * const SEPARATORS = ":|!";
What gives you the idea that those #define
s are a good practice at all? Are you required to handle the great Exclamation Mark Redefinition of 2015?
It is probably safe to assume that an exclamation mark is going to be represented by '!'
now and forever. Just like the constant one is going to be represented by 1
tomorrow as well.
You don't need to define EXCLAMATION_MARK any more than you need to define ONE or MINUS or INT.
精彩评论