我正在尝试使用C++11验证一个单行输入字符串,以查看它是否包含任何前导/尾随空格。我的代码现在看起来像这样:
bool is_valid(const std::string& s) {
auto start = s.begin();
auto end = s.end();
if (std::isspace(*start) || std::isspace(*end)) {
return false;
}
return true;
}
int main() {
std::string name{};
std::getline(std::cin, name);
if (!is_valid(name)) {
std::cout << "Invalid!";
}
return 0;
}
但是现在程序只能检测前导空格。例如,对于 John
它会打印 Invalid!
但对于Mary
它会将其分类为有效输入,这是不正确的。有谁知道我的程序出了什么问题吗?
back()
来检查最后一个字符,不再使用end()
迭代器。 - PaulMcKenzie