sscanf
Read formatted data from strings
Syntax
Description
reads data from A
= sscanf(str
,formatSpec
)str
, converts it according to the format
specified by formatSpec
, and returns the results in an array.
str
is either a character array or a string scalar. The
sscanf
function repeatedly applies
formatSpec
to sequences of characters in
str
until it either reaches the end of str
or fails to match formatSpec
to a sequence of characters. If
str
is a character array with more than one row,
sscanf
reads the characters in column order.
sets the size of the output array to be A
= sscanf(str
,formatSpec
,sizeA
)sizeA
and then reads data
from str
into the output array. sizeA
must be
a positive integer or have the form [m n]
, where
m
and n
are positive integers.
Examples
Convert Character Vector to Numbers
Create a character vector that represents several numbers separated by whitespace characters. Convert the character vector to a column vector of numbers. sscanf
treats whitespace characters as separators between numbers.
chr = '2.7183 3.1416 0.0073'
chr = '2.7183 3.1416 0.0073'
A = sscanf(chr,'%f')
A = 3×1
2.7183
3.1416
0.0073
Convert Text and Resize Output Array
Create a string that represents several numbers and convert it using sscanf
. Specify the size of the output array.
str = "2.7183 3.1416 0.0073"
str = "2.7183 3.1416 0.0073"
A = sscanf(str,'%f',[1 3])
A = 1×3
2.7183 3.1416 0.0073
Convert str
to a 2-by-2 matrix. Because str
represents only three numbers, sscanf
pads A
with enough zeroes to fill in the matrix.
A = sscanf(str,'%f',[2 2])
A = 2×2
2.7183 0.0073
3.1416 0
Count Elements Found in Text
Create a string that contains numbers separated by whitespace characters. Count the elements that sscanf
puts into the output array when it converts the string to numbers.
str = "78 72 64 66 49"
str = "78 72 64 66 49"
Count the elements in the output array A
. Convert the numbers in the string using the %d
operator. %d
matches integers separated by whitespace. To return the number of elements in A
, specify a second output argument.
[A,n] = sscanf(str,'%d')
A = 5×1
78
72
64
66
49
n = 5
Display Error Message
Create a string and read data from it. When sscanf
fails to convert all of the input string, display the error message.
str = "3.14159 are the first 6 digits of pi"
str = "3.14159 are the first 6 digits of pi"
Convert the number in str
. Since str
also contains characters that %f
cannot match, sscanf
returns an error message. sscanf
stops processing as soon as it encounters the word 'are'
because it cannot be converted to a number.
[A,n,errmsg] = sscanf(str,'%f')
A = 3.1416
n = 1
errmsg = 'Matching failure in format.'
Return Last Position Scanned
Create a character vector and read data from it. When sscanf
fails to convert all of the input, return the index that immediately follows the position at which sscanf
stopped. Use this index to display the unscanned input.
chr = '3.14159 are the first 6 digits of pi'
chr = '3.14159 are the first 6 digits of pi'
Convert the data in chr
. Return the index.
[A,~,~,nextindex] = sscanf(chr,'%f')
A = 3.1416
nextindex = 9
Display the characters from chr
that sscanf
did not scan.
chr(nextindex:end)
ans = 'are the first 6 digits of pi'
Match Specified Characters
Create a string that contains several temperatures, indicated by the degree symbol and the letter F
. Convert the temperatures to a numeric array.
To insert the degree symbol (char(176)
), use the insertBefore
function.
T = "78F 72F 64F 66F 49F"; degreeSymbol = char(176); T = insertBefore(T,'F',degreeSymbol)
T = "78°F 72°F 64°F 66°F 49°F"
Return the temperatures as a numeric array.
A = sscanf(T,strcat("%d",degreeSymbol,"F"))
A = 5×1
78
72
64
66
49
Input Arguments
str
— Input text to scan
character array | string scalar
Input text to scan, specified as a character array or string scalar. If
str
is a character array, then it can have multiple
rows, and sscanf
reads the characters in column
order.
Data Types: char
| string
formatSpec
— Format of input fields
formatting operators
Format of the input fields, specified using formatting operators. formatSpec
can
be a character vector in single quotes, or a string scalar.
Numeric Fields
This table lists available conversion specifiers to convert
text to numeric outputs. sscanf
converts
values to their decimal (base 10) representation.
Numeric Field Type | Conversion Specifier | Description |
---|---|---|
Integer, signed |
| Base 10. |
| The values determine the base:
| |
| 64-bit values, base 10, 8, or 16. | |
Integer, unsigned |
| Base 10. |
| Base 8 (octal). | |
| Base 16 (hexadecimal). | |
| 64-bit values, base 10, 8, or 16. | |
Floating-point number |
| Floating-point values. Input fields can contain any
of the following (not case sensitive): |
Character Fields
This table lists available conversion specifiers to convert text so that the output is a character array.
Character Field Type | Conversion Specifier | Description |
---|---|---|
Character vector or string scalar |
| Read the text until |
| Read any single character, including whitespace. | |
Pattern-matching |
| Read only characters in the brackets up to the first nonmatching character or whitespace. Example: |
If formatSpec
contains a combination of numeric
and character specifiers, then sscanf
converts
each character to its numeric equivalent.
Optional Operators
Fields and Characters to Ignore
sscanf
reads all numeric values and characters in sequence, unless you tell it to ignore a particular field or a portion of a field. To skip fields, insert an asterisk (*
) after the percent sign (%
). For example, to skip integers, specify%*d
.Field Width
To specify the maximum number of digits or text characters to read at a time, insert a number after the percent character. For example,
%10c
reads up to 10 characters at a time, including whitespace.%4f
reads up to four digits at a time, including the decimal point.Literal Text to Ignore
sscanf
ignores specified text immediately before or after the conversion specifier.Example:
Level%u
reads'Level1'
as1
.Example:
%uStep
reads'2Step'
as2
.
Data Types: char
| string
sizeA
— Dimensions of output array
Inf
(default) | integer | two-element row vector
Dimensions of the output array, A
, specified
as Inf
, a positive integer, or a two-element row
vector.
Form of | Description |
---|---|
| Read input to the end. |
| Read at most |
| Read at most |
Data Types: double
| single
| int8
| int16
| int32
| int64
| uint8
| uint16
| uint32
| uint64
Output Arguments
A
— Output data
column vector | matrix | character array
Output data, returned as a column vector, matrix, or character
array. The class and size of A
depend on the conversions
specified by formatSpec
and the size of the output
array specified by sizeA
:
If
formatSpec
contains only numeric specifiers, thenA
is a numeric column vector. If you also specify thesizeA
argument, thenA
is a matrix of the specified size, and is padded with zeroes if necessary. If the input contains fewer thansizeA
values, then the size ofA
is smaller thansizeA
. Instead, it is the size required to store the values scanned from the input.If
formatSpec
contains only 64-bit signed integer specifiers, thenA
is of classint64
.If
formatSpec
contains only 64-bit unsigned integer specifiers, thenA
is of classuint64
.Otherwise,
A
is of classdouble
.
If
formatSpec
contains only%c
or%s
specifiers, thenA
is a character vector. If you also specifysizeA
, thenA
is a character array, and is padded as necessary with null characters. (The null character is a control character with the value zero.) If the input contains fewer thansizeA
characters, then the size ofA
is smaller thansizeA
. Instead, it is the size required to store the characters scanned from the input.If
formatSpec
contains a combination of numeric and character specifiers, thenA
is numeric, of classdouble
, andsscanf
converts each character to its numeric equivalent. This conversion occurs even whenformatSpec
explicitly skips all numeric fields (for example,formatSpec
is'%*d %s'
).If
sscanf
cannot match all of the input toformatSpec
, thenA
can be numeric or a character array. The class ofA
depends on the values thatsscanf
reads before it stops processing.
Data Types: double
| int64
| uint64
| char
n
— Number of elements read into output array
integer
Number of elements read into the output array, returned as an integer.
Data Types: double
errmsg
— Error message
character vector
Error message, returned as a character vector. If str
contains any data that sscanf
cannot convert, then
errmsg
contains an error message. If
sscanf
converts all the data successfully, then
errmsg
is an empty character vector.
Data Types: char
nextindex
— Position after last character scanned
integer
Position after the last character scanned, returned as an integer.
Data Types: double
Tips
Format specifiers for the reading functions
sscanf
andfscanf
differ from the formats for the writing functionssprintf
andfprintf
. The reading functions do not support a precision field. The width field specifies a minimum for writing, but a maximum for reading.
Extended Capabilities
C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.
Usage notes and limitations:
The input argument
formatSpec
must be a constant.The
%s
and%[...]
conversion specifiers are not supported.The output arguments
errmsg
andnextinput
are not supported.If you turn off dynamic memory allocation, you must provide the input argument
sizeA
and it must be a constant.In certain cases, the behavior of the generated code might differ from MATLAB®. In such cases, the behavior of the generated code matches that of
sscanf
in the C language. These are some examples:In the generated code, if
sscanf
reads a null byte, the returned values might be truncated.If you read an integer value
x
into an integer format for whichintmax
is smaller thanx
, the MATLAB output saturates atintmax
. In the generated code, this situation can cause an overflow.If you use the formatting specifier
%c
to specify a field width that is greater than the number of characters that are available in the input textstr
, MATLAB returns a string shorter than the specified length that contains only the available characters. The generated code returns a string of the specified length, but the contents of the returned string can vary depending on the C/C++ compiler you use. In some cases, the returned string contains the input string padded with null characters (char(0)
). In other cases, the returned string contains only null characters.
Thread-Based Environment
Run code in the background using MATLAB® backgroundPool
or accelerate code with Parallel Computing Toolbox™ ThreadPool
.
This function fully supports thread-based environments. For more information, see Run MATLAB Functions in Thread-Based Environment.
Version History
Introduced before R2006a
MATLAB Command
You clicked a link that corresponds to this MATLAB command:
Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.
Select a Web Site
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .
You can also select a web site from the following list
How to Get Best Site Performance
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.
Americas
- América Latina (Español)
- Canada (English)
- United States (English)
Europe
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)
Asia Pacific
- Australia (English)
- India (English)
- New Zealand (English)
- 中国
- 日本Japanese (日本語)
- 한국Korean (한국어)