Isupper c что это

от admin

Функция isupper

Обратите внимание на то, что результат, возвращаемый функцией после проверки аргумента, на предмет принадлежности его к прописным буквам, зависит от используемого языка.

Подробно ознакомиться с возвращаемыми результатами функций, для каждого символа стандартного набора символов ASCII вы можете в библиотеке <cctype>.
В С++ локализованная версия функции isupper определена в заголовочном файле <locale> .

Параметры:

  • character
    Символ для проверки, передается в функцию как значение типа int , или EOF .

Возвращаемое значение

Значение, отличное от нуля (т.е. истинно), если аргумент функции — это прописная буква алфавита.

std::isupper

Проверяет, является ли данный символ заглавным, как классифицировано текущей установленной локалью C. В локали «C» по умолчанию isupper возвращает ненулевое значение только для заглавных букв ( ABCDEFGHIJKLMNOPQRSTUVWXYZ ).

Если isupper возвращает ненулевое значение, то гарантируется , что iscntrl , isdigit , ispunct и isspace возврат ноль для того же символа в том же C локали.

Поведение не определено, если значение ch не может быть представлено как unsigned char и не равно EOF .

Parameters

ch характер классификации

Return value

Ненулевое значение,если символ-прописная буква,в противном случае-ноль.

Notes

Как и все другие функции из <cctype> , поведение std::isupper не определено, если значение аргумента не может быть представлено как unsigned char и равно EOF . Чтобы безопасно использовать эти функции с обычными char (или signed char ), аргумент должен быть сначала преобразован в unsigned char :

Точно так же они не должны напрямую использоваться со стандартными алгоритмами, когда типом значения итератора является char или signed char . Вместо этого сначала преобразуйте значение в unsigned char :

C isupper() function

I’m currently reading «The C Programming Language 2nd edition» and I’m not clear about this exercise:

Functions like isupper can be implemented to save space or to save time. Explore both possibilities.

  • How can I implement this function?
  • How should I write two versions, one to save time and one to save space (some pseudo code would be nice)?

I would appreciate some advice about this.

5 Answers 5

Original answer

One version uses an array initialized with appropriate values, one byte per character in the code set (plus 1 to allow for EOF, which may also be passed to the classification functions):

Note that the ‘bits’ can be used by all the various functions like isupper() , islower() , isalpha() , etc with appropriate values for the mask. And if you make the ‘bits’ array changeable at runtime, you can adapt to different (single-byte) code sets.

This takes space — the array.

The other version makes assumptions about the contiguity of upper-case characters, and also about the limited set of valid upper-case characters (fine for ASCII, not so good for ISO 8859-1 or its relatives):

This can (almost) be implemented in a macro; it is hard to avoid evaluating the character twice, which is not actually permitted in the standard. Using non-standard (GNU) extensions, it can be implemented as a macro that evaluates the character argument just once. To extend this to ISO 8859-1 would require a second condition, along the lines of:

Читать:
Dbgeng dll не был найден что делать

Repeat that as a macro very often and the ‘space saving’ rapidly becomes a cost as the bit masking has a fixed size.

Given the requirements of modern code sets, the mapping version is almost invariably used in practice; it can adapt at run-time to the current code set, etc, which the range-based versions cannot.

Extended answer

I still can’t figure out how UPPER_MASK works. Can you explain it more specifically?

Ignoring issues of namespaces for symbols in headers, you have a series of twelve classification macros:

  • isalpha()
  • isupper()
  • islower()
  • isalnum()
  • isgraph()
  • isprint()
  • iscntrl()
  • isdigit()
  • isblank()
  • isspace()
  • ispunct()
  • isxdigit()

The distinction between isspace() and isblank() is:

  • isspace() — space ( ‘ ‘ ), form feed ( ‘\f’ ), new-line ( ‘\n’ ), carriage return ( ‘\r’ ), horizontal tab ( ‘\t’ ), and vertical tab ( ‘\v’ ).
  • isblank() — space ( ‘ ‘ ), and horizontal tab ( ‘\t’ ).

There are definitions for these sets of characters in the C standard, and guidelines for the C locale.

For example (in the C locale), either islower() or isupper() is true if isalpha() is true, but that need not be the true in other locales.

I think the necessary bits are:

  • DIGIT_MASK
  • XDIGT_MASK
  • ALPHA_MASK
  • LOWER_MASK
  • UPPER_MASK
  • PUNCT_MASK
  • SPACE_MASK
  • PRINT_MASK
  • CNTRL_MASK
  • BLANK_MASK

From these ten masks, you can create the other two:

  • ALNUM_MASK = ALPHA_MASK | DIGIT_MASK
  • GRAPH_MASK = ALNUM_MASK | PUNCT_MASK

Superficially, you can also use ALPHA_MASK = UPPER_MASK | LOWER_MASK , but in some locales, there are alphabetic characters that are neither upper-case nor lower-case.

So, we can define masks as follows:

The data for the character set; the data shown is for the first half of ISO 8859-1, but is the same for the first half of all the 8859-x code sets. I’m using C99 designated initializers as a documentary aid, even though the entries are all in order:

Функция isupper() в C++

Функция isupper() в C++ проверяет, является ли данный символ символом верхнего регистра или нет.

Функция isupper() проверяет, находится ли ch в верхнем регистре в соответствии с текущей локалью C. По умолчанию символы от A до Z (значение ascii от 65 до 90) являются прописными.

Поведение isupper() не определено, если значение ch не может быть представлено как unsigned char или не равно EOF.

Параметры

Возвращаемое значение

Функция isupper() возвращает ненулевое значение, если ch в верхнем регистре, в противном случае возвращает ноль.

Похожие статьи