我正在尝试查看正在读取的字符串的结尾是否为".如果不是,我希望它打印出来的东西.
if(!line.find_last_of("\"")) {
cout << "Extra parameter is typed.";
continue;
Run Code Online (Sandbox Code Playgroud)
我试图使用find_last_of但是当我运行它时,无论命令是否有额外的参数,都会打印额外的参数.例:
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.
Run Code Online (Sandbox Code Playgroud)
虽然我认为@Jonathon Seng的答案很好(而且已经投了票),但我认为还有另一种可能值得一提的可能性.而不是mystring.at(mystring.length()-1),你可以使用*mystring.rbegin():
if (*line.rbegin() == '"') ...
Run Code Online (Sandbox Code Playgroud)
当然,您仍然需要检查字符串是否也为空.对于这一点,我通常喜欢!line.empty()过line.length() > 0,所以最终版本将变为:
if (!line.empty() && *line.rbegin() == '"') {
// whatever
}
Run Code Online (Sandbox Code Playgroud)
编辑:请注意,测试!line.empty()必须是第一个.&&计算其左操作数,然后如果(并且仅当)求值true,则计算其右操作数.我们需要确认该行不为空第一,然后检查只有当该字符串不是非空的字符.