the code that I'm currently working with looks like this:
if ((text.at(text.size() -1 ) != '!' ) && (text.at(text.size() -1 ) != '?') && (text.at(text.size() -1 ) != ':' ) && (text.at(text.size() -1 ) != ',' ) && (text.at(text.size() -1 ) != ';' ) && (text.at(text.size() -1 ) != '=' ) )
The details of it aren't terribly important but I'm basically trying to make a kind of word processor that only uses the command prompt, and whenever the user presses enter with nothing in the input buffer, the program closes because it's being terminated in "an unusual way" which I'm taking to mean that this line of code is trying to reference a position in the string that doesn't exist, i.e. -1. So I need a new way to reference the last character in a given string variable that can still work with the line of code given. Thanks for your help!
2 Answers 2
You should check text is not empty before access its element and use std::string::rbegin or std::string::back(needs C++11) to simplify your code.
you call it this way:
if (!text.empty())
{
char c = *text.rbegin();
if (c != '!' &&
c != '?' &&
c != ':' &&
c != ',' &&
c != ';' &&
c != '=' )
{
}
}
To enhance code readability, you could introduce a local variable in this situation, it's cheap to make a copy of a char and you can shorten your if statement a lot.
12 Comments
*text.rbegin() != '!', right? It doesn't need other lib(text.at(rbegin()) != '!' ). Cheers for the help!at on an empty string, and getting an exception. You've simply modified it to dereference an invalid iterator, leading to undefined behavior. He probably thinks the problem is solved, because the program isn't crashing, because instead of an exception, he's getting undefined behavior.Seems easy enough, just check for text.size() > 0 first
if (text.size() > 0 &&
text.at(text.size() - 1) != '!' &&
text.at(text.size() - 1) != '?' &&
text.at(text.size() - 1) != ':' &&
text.at(text.size() - 1) != ',' &&
text.at(text.size() - 1) != ';' &&
text.at(text.size() - 1) != '=')
or maybe you intended this logic (it's not really clear from your question)
if (text.size() == 0 ||
(text.at(text.size() - 1) != '!' &&
text.at(text.size() - 1) != '?' &&
text.at(text.size() - 1) != ':' &&
text.at(text.size() - 1) != ',' &&
text.at(text.size() - 1) != ';' &&
text.at(text.size() - 1) != '='))
You should also simplify that expression, it's way too complex.
!text.empty()first.string::at()also throws anout_of_rangeexception if you try to go beyond its bounds.