Reputation: 51
I'm trying to see if the end of the string being read is a "
. If it isn't, I want it to print out something.
if(!line.find_last_of("\"")) {
cout << "Extra parameter is typed.";
continue;
I was trying to use find_last_of
but when I run it extra parameter is printed no matter if it the command has extra parameters. Example:
lc "file.txt" -suppose to true so it's suppose to continue program but returns false
lc "file.txt" lk - suppose to return false and it does but should only return false for this type of case.
Upvotes: 1
Views: 998
Reputation: 490338
Although I think @Jonathon Seng's answer is good (and have up-voted it), I think there's another possibility that might be worth mentioning. Instead of mystring.at(mystring.length()-1)
, you could use *mystring.rbegin()
:
if (*line.rbegin() == '"') ...
Of course, you still have to check that the string isn't empty as well. For this, I'd normally prefer !line.empty()
over line.length() > 0
, so the final version becomes:
if (!line.empty() && *line.rbegin() == '"') {
// whatever
}
Edit: note that the test for !line.empty()
must be first. &&
evaluates its left operand, and then if (and only if) that evaluates to true
, evaluates its right operand. We need to verify that the line isn't empty first, then check the character only if the string isn't non-empty.
Upvotes: 6
Reputation: 638
One way to do this might be
if( (!(line.find_last_of("\"") == line.length() - 1)) && (line.length() > 0) ) {
<do your stuff>;
}
Since string::find_last_of() returns the last position of the given character if it is found (at least once) anywhere in the line. So if it is the second-to-last character, it will return line.length()-2 which will cause your boolean expression (the if condition) to behave the same way as it if was the last character.
Checking that line.length()
is greater than zero is essential as if line.length() == 0
, this may return true since string::find_last_of()
returns string::npos
(which typically equals -1) if it cannot find the matching pattern.
Also don't forget to null-check line
but that's a given if you like programming defensively.
Upvotes: 0
Reputation: 1219
You could compare line.at(line.length() - 1)
to '"'
(after establishing line.length() > 0
).
Upvotes: 2