Espaços nominais
Variantes
Ações

wscanf, fwscanf, swscanf

De cppreference.com
< c | io

<metanoindex/>

 
 
File input/output
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.
Arquivo de acesso
Original:
File access
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Directa de entrada / saída
Original:
Direct input/output
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Não formatado entrada / saída
Original:
Unformatted input/output
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Formatado de entrada / saída
Original:
Formatted input/output
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Arquivo de posicionamento
Original:
File positioning
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
De tratamento de erros
Original:
Error handling
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Operações em arquivos
Original:
Operations on files
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 <wchar.h>
int wscanf( const wchar_t* format, ... );
(1)
int fwscanf( FILE *stream, const wchar_t* format, ... );
(2)
int swscanf( const wchar_t* buffer, const wchar_t* format, ... );
(3)
Lê os dados do uma variedade de fontes, interpreta-o de acordo com format e armazena os resultados em determinados locais.
Original:
Reads data from the a variety of sources, interprets it according to format and stores the results into given locations.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
1)
Lê os dados a partir de stdin.
Original:
Reads the data from stdin.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
2)
Lê os dados do fluxo de arquivo stream.
Original:
Reads the data from file stream stream.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
3)
Lê os dados terminada em nulo buffer corda larga.
Original:
Reads the data from null-terminated wide string buffer.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

Parâmetros

stream -
fluxo de arquivo de entrada para ler
Original:
input file stream to read from
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
buffer -
ponteiro para uma string terminada em null gama de ler
Original:
pointer to a null-terminated wide string to read from
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
format -
ponteiro para uma string terminada em null ampla especificando como ler a entrada.
Original:
pointer to a null-terminated wide string specifying how to read the input.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
... -
receber argumentos
Original:
receiving arguments
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

Número de argumentos lidos com êxito ou EOF se ocorrer uma falha antes de ler o primeiro argumento.
Original:
Number of arguments successfully read, or EOF if failure occurs before the first receiving argument was assigned.
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>              // para fopen(), feof(), fprintf() e fclose()
#include <wchar.h>              // para wscanf(), fwscanf() e wprintf() 
#include <string.h>             // para strlen()

#define NUM_VARS       3
#define NUM_ITENS      3
#define ERRO_LEITURA   2
#define ERRO_ESCRITA   3
#define NUM_REGISTROS  3

wchar_t* dados[] = {
    L"bananas 1.99 23",
    L"peras 2.15 17",
    L"morangos 2.99 34"
};

struct frutas_t {
    wchar_t nome[20];
    double preco;
    unsigned int quantidade;
};

int main(void) {
    FILE* fp = tmpfile();
    char str[] = "Mississipi Jackson 420000 807";
    wchar_t estado[20];
    wchar_t capital[20];
    unsigned int populacao = 0;
    int elevacao = 0;
    int idade = 0;
    float pi = 0;

    printf("Entre o estado, idade e o valor de PI: ");
    if (wscanf(L"%ls%d%f", estado, &idade, &pi) != NUM_VARS) {
        fprintf(stderr, "Erro lendo dados de entrada.\n");
        return ERRO_LEITURA;
    }
    wprintf(L"Estado: %ls\nIdade : %d anos\nPI    : %.5f\n\n", estado, idade, pi);

    if (fp) {
        // escreve os dados da variável str (array) no arquivo temporário
        if (fwrite(str, strlen(str), NUM_ITENS, fp) != NUM_ITENS) {
            fprintf(stderr, "Erro escrevendo no arquivo temporário.\n");
            return ERRO_ESCRITA;
        }
        // reseta o ponteiro do arquivo
        rewind(fp);

        // Lê dados do arquivo e guarda nas variáveis
        fwscanf(fp, L"%ls%ls%u%d", estado, capital, &populacao, &elevacao);
        wprintf(L"Estado : %ls\nCapital: %ls\nPopulação de Jackson (em 2020): %u\n"
                L"Ponto mais alto: %d pés\n", 
                estado, capital, populacao, elevacao);
        fclose(fp);
    }

    // uso do swscanf()
    struct frutas_t frutas[NUM_REGISTROS];

    for (int i = 0; i < NUM_REGISTROS; i++) {
        // Lê o registro e guarda os dados nas variáveis dentro da estrutura frutas
        swscanf(dados[i], L"%ls%lf%u", 
                frutas[i].nome, &frutas[i].preco, &frutas[i].quantidade);
    }

    for (int i = 0; i < NUM_REGISTROS; i++) {
        // Imprime os dados que estão na estrutura.
        wprintf(L"Fruta: %ls\nPreço: $%.2lf\nQuantidade: %u\n\n", 
                frutas[i].nome, frutas[i].preco, frutas[i].quantidade);
    }
}

Saída:

// Possível saída informada pelo usuário.
Estado: California
Idade : 170 anos
PI    : 3.14159

// Dados provenientes do arquivo temporário.
Estado : Mississipi
Capital: Jackson
Populaçâo de Jackson (em 2020): 420000
Ponto mais alto: 807 pés

// Saída da impressão dos registros contendo frutas
Fruta: bananas
Preço: $1.99
Quantidade: 23

Fruta: peras
Preço: $2.15
Quantidade: 17

Fruta: morangos
Preço: $2.99
Quantidade: 34

Veja também

lê a entrada de caracteres formatada variedade de stdin, um stream
arquivo ou um buffer usando lista de argumentos variável
Original:
reads formatted wide character input from stdin, a file stream
or a buffer using variable argument list
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 wscanf, fwscanf, swscanf