Namespaces
Variants
Views
Actions

scanf, fscanf, sscanf

From cppreference.com
< c‎ | io
Revision as of 15:55, 23 October 2013 by P12 (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Defined in header <stdio.h>
(1)
int scanf( const char          *format, ... );
(until C99)
int scanf( const char *restrict format, ... );
(since C99)
(2)
int fscanf( FILE          *stream, const char          *format, ... );
(until C99)
int fscanf( FILE *restrict stream, const char *restrict format, ... );
(since C99)
(3)
int sscanf( const char          *buffer, const char          *format, ... );
(until C99)
int sscanf( const char *restrict buffer, const char *restrict format, ... );
(since C99)

Reads data from the a variety of sources, interprets it according to format and stores the results into given locations.

1) reads the data from stdin
2) reads the data from file stream stream
3) reads the data from null-terminated character string buffer

Contents

[edit] Parameters

stream - input file stream to read from
buffer - pointer to a null-terminated character string to read from
format - pointer to a null-terminated character string specifying how to read the input.

The format string consists of whitespace characters (any single whitespace character in the format string consumes all available consecutive whitespace characters from the input), non-whitespace characters except % (each such character in the format string consumes exactly one identical character from the input) and conversion specifications. Each conversion specification has the following format:

  • introductory % character
  • (optional) assignment-suppressing character *. If this option is present, the function does not assign the result of the conversion to any receiving argument.
  • (optional) integer number (greater than zero) that specifies maximum field width, that is, the maximum number of characters that the function is allowed to consume when doing the conversion specified by the current conversion specification. Note that %s and %[ may lead to buffer overflow if the width is not provided.
  • (optional) length modifier that specifies the size of the receiving argument, that is, the actual destination type. This affects the conversion accuracy and overflow rules. The default destination type is different for each conversion type (see table below).
  • conversion format specifier

The following format specifiers are available:

Conversion
specifier
Explanation Argument type
length modifier hh h (none) l ll j z t L
% matches literal % N/A N/A N/A N/A N/A N/A N/A N/A N/A
c matches a single character N/A N/A
char*
wchar_t*
N/A N/A N/A N/A N/A
s matches a character string (a sequence of non-whitespace characters)
[set]
matches a non-empty sequence of character from set of characters.

If the first character of the set is ^, then all characters not in the set are matched. If the set begins with ] or ^] then the ] character is also included into the set.

d
matches a decimal integer.

The format of the number is the same as expected by strtol() with the value 10 for the base argument

signed char* or unsigned char*
signed short* or unsigned short*
signed int* or unsigned int*
signed long* or unsigned long*
signed long long* or unsigned long long*
N/A
i
matches a decimal integer.

The format of the number is the same as expected by strtol() with the value 0 for the base argument

u
matches a unsigned decimal integer.

The format of the number is the same as expected by strtoul() with the value 0 for the base argument

o
matches an octal integer.

The format of the number is the same as expected by strtol() with the value 8 for the base argument

x
matches an hexadecimal integer.

The format of the number is the same as expected by strtol() with the value 16 for the base argument

n
returns the number of characters read so far.

No input is consumed. Does not increment the assignment count. If the specifier has assignment-suppressing operator defined, the behavior is undefined

a, A
e, E
f, F
g, G
matches a floating-point number.

The format of the number is the same as expected by strtof()

N/A N/A
float*
double*
N/A N/A N/A N/A
long double*
p
matches implementation defined character sequence defining a pointer.

printf family of functions should produce the same sequence using %p format specifier

N/A N/A
void**
N/A N/A N/A N/A N/A N/A

All conversion specifiers other than [, c, and n consume and discard all leading whitespace characters before attempting to parse the input. These consumed characters do not count towards the specified maximum field width.

The conversion specifiers lc, ls, and l[ perform multibyte-to-wide character conversion as if by calling mbrtowc with an mbstate_t object initialized to zero before the first character is converted.

The conversion specifiers s and [ always store the null terminator in addition to the matched characters. The size of the destination array must be at least one greater than the specified field width.

The correct conversion specifications for the fixed-width character types (int8_t, etc) are defined in the header <cinttypes>.


... - receiving arguments

[edit] Return value

Number of receiving arguments successfully assigned, or EOF if read failure occurs before the first receiving argument was assigned.

[edit] Example

#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <locale.h>
 
int main(void)
{
    // prepare a file, filled with numbers, squares, and factorials
    FILE *fp = fopen("results.dat", "w");
    if (fp == NULL) {
        perror("couldn't open results.dat for writing: ");
        return EXIT_FAILURE;
    }
    int product = 1;
    for (int i=1; i<=10; ++i) {
        fprintf(fp, "i=%d, i^2=%d, factorial(%d)=%d\n", i, i*i, i, product*=i);
    }
    fclose(fp);
 
    // now parse the file with fscanf()
    fp = fopen("results.dat", "r");
    if (fp == NULL) {
        perror("couldn't open results.dat for reading: ");
        return EXIT_FAILURE;
    }
 
    int n, sq, fact;
    while (fscanf(fp, "i=%d, i^2=%d, factorial(%*d)=%d ", &n, &sq, &fact) == 3) {
        printf("factorial(%d) = %d\n", n, fact);
    }
    fclose(fp);
 
    // sample string to parse with sscanf()
    char input[] = "25 54.32E-1 Thompson 56789 0123 56ß水";
    /* parse as follows:
       an integer, a floating-point value, a word,
       two-digit integer (digits 5 and 6)
       a floating-point value (digits 7, 8, 9)
       an integer which isn't stored anywhere
       a string of integers (digits 5 and 6)
       two wide characters, using multibyte to wide conversion */
 
    int i, j;
    float x, y;
    char str1[10], str2[4];
    wchar_t warr[2];
    setlocale(LC_ALL, "en_US.utf8");
 
    int ret = sscanf(input, "%d%f%9s%2d%f%*d %3[0-9]%2lc",
                     &i, &x, str1, &j, &y, str2, warr);
 
    printf("Converted %d fields:\ni = %d\nx = %f\nstr1 = %s\n"
                      "j = %d\ny = %f\nstr2 = %s\n"
                      "warr[0] = U+%x warr[1] = U+%x\n",
                      ret, i, x, str1, j, y, str2, warr[0], warr[1]);
    return EXIT_SUCCESS;
}

Output:

factorial(1) = 1
factorial(2) = 2
factorial(3) = 6
factorial(4) = 24
factorial(5) = 120
factorial(6) = 720
factorial(7) = 5040
factorial(8) = 40320
factorial(9) = 362880
factorial(10) = 3628800
Converted 7 fields:
i = 25
x = 5.432000
str1 = Thompson
j = 56
y = 789.000000
str2 = 56
warr[0] = U+df warr[1] = U+6c34

[edit] See also

(C99)(C99)(C99)
reads formatted input from stdin, a file stream or a buffer
using variable argument list
(function) [edit]
gets a character string from a file stream
(function) [edit]
prints formatted output to stdout, a file stream or a buffer
(function) [edit]
C++ documentation for scanf, fscanf, sscanf