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
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
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 zeros to fill in the matrix.
A = sscanf(str,'%f',[2 2])A = 2×2
2.7183 0.0073
3.1416 0
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
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 = 'Input file or string does not contain specified format.'
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'
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
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
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
sscanfreads 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,
%10creads up to 10 characters at a time, including whitespace.%4freads up to four digits at a time, including the decimal point.Literal Text to Ignore
sscanfignores specified text immediately before or after the conversion specifier.Example:
Level%ureads'Level1'as1.Example:
%uStepreads'2Step'as2.
Data Types: char | string
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
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
formatSpeccontains only numeric specifiers, thenAis a numeric column vector. If you also specify thesizeAargument, thenAis a matrix of the specified size, and is padded with zeros if necessary. If the input contains fewer thansizeAvalues, then the size ofAis smaller thansizeA. Instead, it is the size required to store the values scanned from the input.If
formatSpeccontains only 64-bit signed integer specifiers, thenAis of classint64.If
formatSpeccontains only 64-bit unsigned integer specifiers, thenAis of classuint64.Otherwise,
Ais of classdouble.
If
formatSpeccontains only%cor%sspecifiers, thenAis a character vector. If you also specifysizeA, thenAis 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 thansizeAcharacters, then the size ofAis smaller thansizeA. Instead, it is the size required to store the characters scanned from the input.If
formatSpeccontains a combination of numeric and character specifiers, thenAis numeric, of classdouble, andsscanfconverts each character to its numeric equivalent. This conversion occurs even whenformatSpecexplicitly skips all numeric fields (for example,formatSpecis'%*d %s').If
sscanfcannot match all of the input toformatSpec, thenAcan be numeric or a character array. The class ofAdepends on the values thatsscanfreads before it stops processing.
Data Types: double | int64 | uint64 | char
Number of elements read into the output array, returned as an integer.
Data Types: double
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
Position after the last character scanned, returned as an integer.
Data Types: double
Tips
Format specifiers for the reading functions
sscanfandfscanfdiffer from the formats for the writing functionssprintfandfprintf. The reading functions do not support a precision field. The width field specifies a minimum for writing, but a maximum for reading.
Extended Capabilities
Usage notes and limitations:
The input argument
formatSpecmust be a constant.The
%sand%[...]conversion specifiers are not supported.The output arguments
errmsgandnextinputare not supported.If you turn off dynamic memory allocation, you must provide the input argument
sizeAand 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
sscanfin the C language. These are some examples:In the generated code, if
sscanfreads a null byte, the returned values might be truncated.If you read an integer value
xinto an integer format for whichintmaxis smaller thanx, the MATLAB output saturates atintmax. In the generated code, this situation can cause an overflow.If you use the formatting specifier
%cto 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.
Refer to the usage notes and limitations in the C/C++ Code Generation section. The same usage notes and limitations apply to GPU code generation.
The sscanf 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.
Seleccione un país/idioma
Seleccione un país/idioma para obtener contenido traducido, si está disponible, y ver eventos y ofertas de productos y servicios locales. Según su ubicación geográfica, recomendamos que seleccione: .
También puede seleccionar uno de estos países/idiomas:
Cómo obtener el mejor rendimiento
Seleccione China (en idioma chino o inglés) para obtener el mejor rendimiento. Los sitios web de otros países no están optimizados para ser accedidos desde su ubicación geográfica.
América
- América Latina (Español)
- Canada (English)
- United States (English)
Europa
- 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)