2012-07-26 40 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