strtoul, strtoull
![]() |
This page has been machine-translated from the English version of the wiki using Google Translate.
The translation may contain errors and awkward wording. Hover over text to see the original version. You can help to fix errors and improve the translation. For instructions click here. |
Definido no cabeçalho <stdlib.h>
|
||
unsigned long strtoul( const char *str, char **str_end, int base ); |
||
unsigned long long strtoull( const char *str, char **str_end, int base ); |
||
str
.str
.You can help to correct and verify the translation. Click here for instructions.
Function discards any whitespace characters until first non-whitespace character is found. Then it takes as many characters as possible to form a valid base-n (where n=base) unsigned integer number representation and converts them to an integer value. The valid unsigned integer value consists of the following parts: None
- (opcional) prefix (
0
) indicating octal base (applies only when the base is 8) - (opcional) prefix (
0x
or0X
) indicating hexadecimal base (applies only when the base is 16) - a sequence of digits
The set of valid digits for base-2 integer is 01
, for base-3 integer is 012
, and so on. For bases larger than 10
, valid digits include alphabetic characters, starting from Aa
for base-11 integer, to Zz
for base-36 integer. The case of the characters is ignored.
You can help to correct and verify the translation. Click here for instructions.
str_end
para o próximo carácter depois do último carácter lido. Se str_end
for nulo, ele é ignorado.str_end
to point to the character past the last character interpreted. If str_end
is NULL, it is ignored.You can help to correct and verify the translation. Click here for instructions.
Índice |
[editar] Parâmetros
str | - | ponteiro para o byte string terminada em nulo para ser interpretado
Original: pointer to the null-terminated byte string to be interpreted The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. |
str_end | - | ponteiro para um ponteiro para caracter .
Original: pointer to a pointer to character. The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. |
base | - | Base do valor inteiro interpretado
Original: base of the interpreted integer value The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. |
[editar] Valor de retorno
str
em caso de sucesso. Se o valor convertido cai fora do alcance do tipo de retorno correspondente, o erro ocorre e intervalo ULONG_MAX ou ULLONG_MAX é devolvido. Se nenhuma conversão pode ser executada, é devolvido 0.str
on success. If the converted value falls out of range of corresponding return type, range error occurs and ULONG_MAX or ULLONG_MAX is returned. If no conversion can be performed, 0 is returned.You can help to correct and verify the translation. Click here for instructions.
[editar] Exemplo
#include <stdio.h> #include <stdlib.h> void main(void) { char* dados[] = { "1000", "2000", "3000", "4000", "5000" }; // UL no final do número indica que o número deve ser interpretado como um 'longo sem // sinal', ou seja, não negativo. unsigned long soma = 0UL; // Calcula o tamanho do array (quantos elementos ele tem) size_t tamanho = sizeof(dados)/sizeof(dados[0]); for (size_t i = 0; i < tamanho; i++) { // Nesta conversão não estamos preocupados com o segundo parâmetro, // portanto passamos NULL (nulo). soma += strtoul(dados[i], NULL, 10); } printf("A soma do array é: %lu\n\n", soma); char fruta[] = "28 bananas."; char* fim_da_leitura; // O segundo parâmetro da função strtoul() é do tipo char** (ponteiro para um ponteiro) // como a variável fim_da_leitura é um ponteiro (char*), nós precisamos extrair o seu // endereço de memória através do carácter & para convertê-la em um char** (ponteiro // para ponteiro). unsigned long total_bananas = strtoul(fruta, &fim_da_leitura, 10); printf("Total de bananas: %lu\nA leitura parou no string: '%s'\n\n", total_bananas, fim_da_leitura); // Como podemos observar na saída acima, o total de 28 bananas foi impresso e a leitura // parou quando encontrou o carácter ' ', que não é numérico, entre o número 28 e a // palavra bananas. // O que acontece quando temos uma situação inversa? Um carácter não numérico aparece // antes do carácter numérico. No exemplo abaixo podemos verificar que a conversão não // ocorreu e o ponteiro que aponta para os caracteres que foram lidos, está apontando // para o início do string. char letras_numeros[] = "abc 123"; unsigned long numero = strtoul(letras_numeros, &fim_da_leitura, 10); printf("numero: %lu\nfim_da_leitura: '%s'\n", numero, fim_da_leitura); // A função strtoull(), string para unsigned long long, funciona da mesma maneira que // a função strtoul(), usando os mesmos tipos de parâmetros. A única diferença é que // ela returna um número do tipo unsigned long long (longo longo não negativo), quando // a conversão é bem sucedida, caso contrário, ela retorna 0. unsigned long long numero_longo = strtoull("1234567890987654321", NULL, 10); // Note que para unsigned long long usamos %llu em vez de %lu que usamos no exemplo // acima. printf("numero_longo: %llu\n", numero_longo); }
Saída:
A soma do array é: 15000 Total de bananas: 28 A leitura parou no string: ' bananas.' numero: 0 fim_da_leitura: 'abc 123' numero_longo: 1234567890987654321
[editar] Veja também
converte uma seqüência de byte para um valor inteiro Original: converts a byte string to an integer value The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. (função) | |
converte uma seqüência de byte para um valor inteiro Original: converts a byte string to an integer value The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. (função) | |
C++ documentation for strtoul
|