2012-07-26 47 views

回答

1

考虑输入string

bool flag = true; 
for(int i = 0; i < input.length(); ++i) { 
if (input[i] < 'A' || input[i] > 'Z') { 
    flag = false; 
    break; 
} 
} 

然后flag显示你想要什么。 如果您使用其他字符表(非ASCII,Unicode),那么您可以使用从cctype

+1

不可移植 - 例如,如果您使用的是EBCDIC,则会接受诸如},{和\等字符。它宁愿使用'std :: find_if'。 – Flexo 2012-07-26 06:40:25

+0

如何使用'isupper'? http://www.cplusplus.com/reference/clibrary/cctype/isupper/ – 2012-07-26 06:41:48

+1

@Flexo:可移植性是相对的。你很可能会遇到一个不可能编写C++的系统,而不是使用EBCDIC的系统。 – 2012-07-26 06:42:01

5

假设input是一个字符串,您可以使用std::find_if检查任何非大写字符来查找不合适的第一个字符。

#include <iostream> 
#include <algorithm> 
#include <cctype> 
#include <string> 

int main() { 
    std::string input; 
    std::cin >> input; 
    std::cout << (std::find_if(input.begin(), input.end(), std::isupper) != input.end()) << "\n"; 
} 

如果你有C++ 11,简化了轻微进一步:

std::all_of(input.begin(), input.end(), std::isupper) 
+4

或者看看[std :: any_of/all_of/none_of](http://en.cppreference.com/w/cpp/algorithm/all_any_none_of)。 – 2012-07-26 06:57:07

+0

@ BenjaminLindley,好点。我忘记了存在。 – chris 2012-07-26 07:00:46

+0

@BenjaminLindley - 有趣的我没有意识到他们已经被添加到C++ 11中。 – Flexo 2012-07-26 07:03:03