【发布时间】:2016-03-10 20:51:14
【问题描述】:
这里是 C++ 初学者,第一次上编程课。我正在尝试编写一个程序来识别字符串是否全部小写。我得到了下面的代码。但是,我需要考虑空格“”。如果用户输入的字符串中有空格,则程序假定返回它不是全部小写。示例:
输入:abc def return:字符串不是小写的。
你们中的任何人是否会这么好心地建议在下面的代码中解决这个问题的最佳方法是什么?
注意:我知道我已经“包含”了一些额外的头文件,但那是因为这将成为另一个程序的一部分,这只是让事情运行的摘录。
非常感谢大家!!
#include <fstream>
#include <iostream>
#include <string>
#include <cstdlib>
#include <algorithm>
#include <cctype>
#include <iomanip>
using namespace std;
bool die(const string & msg);
bool allLower(const string & l);
int main() {
string l;
cout << "\nEnter a string (all lower case?): ";
cin >> l;
if (allLower(l) == true)
{
cout << "The string is lower case." << endl;
}
else
{
cout << "The string is not lower case." << endl;
}
}
bool allLower(const string & l) {
struct IsUpper {
bool operator()(int value) {
return ::isupper((unsigned char)value);
}
};
return std::find_if(l.begin(), l.end(), IsUpper()) == l.end();
}
bool die(const string & msg){
cout << "Fatal error: " << msg << endl;
exit(EXIT_FAILURE);
}
【问题讨论】:
-
就像
::isupper有类似::isspace的函数来检查空格
标签: c++ string boolean uppercase lowercase