Espaços nominais
Variantes
Ações

strtoul, strtoull

De cppreference.com
< c | string | byte

<metanoindex/>

 
 
 
Cordas de terminação nula de bytes
Funções
Original:
Functions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Manipulação personagem
Original:
Character manipulation
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Conversões para formatos numéricos
Original:
Conversions to numeric formats
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Manipulação de cadeia
Original:
String manipulation
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Exame String
Original:
String examination
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Manipulação de memória
Original:
Memory manipulation
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Diversos
Original:
Miscellaneous
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
 
<tbody> </tbody>
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 );
Interpreta um valor inteiro sem sinal em uma seqüência de bytes apontado por str.
Original:
Interprets an unsigned integer value in a byte string pointed to by str.
The text has been machine-translated via Google Translate.
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 or 0X) 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.

Os dígitos válidos para a base-2 inteiros são 01, para base-3 inteiros são 012, e assim por diante. Para bases maiores que 10, dígitos válidos incluem caracteres alfanuméricos, começando com a letra Aa para base-11 inteiros, até Zz para base-36 inteiros. Pode-se usar letras maiúsculas ou letras minúsculas.
Original:
{{{2}}}
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
As funções movem o ponteiro str_end para o próximo carácter depois do último carácter lido. Se str_end for nulo, ele é ignorado.
Original:
The functions sets the pointer pointed to by str_end to point to the character past the last character interpreted. If str_end is NULL, it is ignored.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

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.

Valor de retorno

Valor inteiro correspondente ao conteúdo do 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.
Original:
Integer value corresponding to the contents of 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.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

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

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) [edit]
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) [edit]
C++ documentation for strtoul
Morty Proxy This is a proxified and sanitized view of the page, visit original site.