How to Read a Number in C Using Sscanf and Fgets
| | This page may need to verify facts by citing reliable publications. You can aid by adding references to reliable publications, or by correcting statements cited as fact. |
scanf is a function that reads information with specified format from a given string stream source, originated from C programming language, and is present in many other programming languages.
The scanf function prototype is:
-
int scanf ( const char * format , ...);
The role returns the total number of items successfully matched, which tin be less than the number requested. If the input stream is wearied or reading from it otherwise fails before any items are matched, EOF is returned.
So far as is traceable, "scanf" stands for "scan format", because it scans the input for valid tokens and parses them according to a specified format.
Usage [edit | edit source]
The scanf function is institute in C, in which information technology reads input for numbers and other datatypes from standard input (often a command line interface or similar kind of a text user interface).
The following shows lawmaking in C that reads a variable number of unformatted decimal integers from the standard input and prints out each of them on a separate line:
#include <stdio.h> int main ( void ) { int n ; while ( scanf ( "%d" , & n )) printf ( "%d \n " , due north ); return 0 ; } After being processed past the program above, a messy list of integers such as
456 123 789 456 12 456 1 2378
will appear neatly as:
456 123 789 456 12 456 1 2378
To print out a discussion:
#include <stdio.h> int main ( void ) { char give-and-take [ 20 ]; if ( scanf ( "%19s" , word ) == 1 ) puts ( discussion ); render 0 ; } No matter what the datatype the programmer wants the programme to read, the arguments (such equally &n above) must be pointers pointing to memory. Otherwise, the part will non perform correctly because information technology will be attempting to overwrite the wrong sections of memory, rather than pointing to the memory location of the variable yous are attempting to get input for.
As scanf is designated to read only from standard input, many programming languages with interfaces, such as PHP, have derivatives such equally sscanf and fscanf but non scanf itself.
Derivatives [edit | edit source]
Depending on the actual source of input, programmers can use different derivatives of scanf. Two common examples are sscanf and fscanf.
fscanf [edit | edit source]
The fscanf derivative reads input from a specified file stream. The prototypes are every bit follows:
(C or C++)
int fscanf ( FILE * file , const char * format , ...); (PHP)
mixed fscanf ( resources file , const string format [, mixed args ... ]) The fscanf derivative works like the original scanf office - parts of the input, once read, will not be read once again until the file is airtight and reopened.
sscanf [edit | edit source]
The sscanf derivative reads input from a character cord passed as the first argument. Ane important different from fscanf is that the string is read from the starting time every time the function is chosen. There is no 'pointer' that is incremented upon a successful read functioning. The prototypes are as follows:
(C or C++)
int sscanf ( const char * str , const char * format , ...); (PHP)
mixed sscanf ( const string str , const string format [, mixed args ... ]) vscanf, vsscanf, and vfscanf [edit | edit source]
int vscanf ( const char * format , va_list args ); int vsscanf ( const char * source , const char * format , va_list args ); int vfscanf ( FILE * file , const char * format , va_list args ); These are similar the same functions without the 5 prefix, except they take their arguments from a va_list. (Encounter stdarg.h.) These variants may be used in variable-argument functions.
Format cord specifications [edit | edit source]
The formatting placeholders in scanf are more than or less the same as that in printf, its contrary office.
There are rarely constants (i.e. characters that are not formatting placeholders) in a format string, mainly because a program is usually non designed to read known information. The exception is one or more whitespace characters, which discards all whitespace characters in the input.
Some of the virtually commonly used placeholders follow:
-
%d: Browse an integer equally a signed decimal number. -
%i: Scan an integer equally a signed number. Like to%d, simply interprets the number as hexadecimal when preceded by0xand octal when preceded by0. For instance, the string031would be read as 31 using%d, and 25 using%i. The flaghin%howdyindicates conversion to abrusqueandhhconversion to achar. -
%u: Scan for decimalunsigned int(Notation that in the C99 standard the input value minus sign is optional, so if a negative number is read, no errors will arise and the result volition be the two'south complement. Encounterstrtoul().Template:Failed verification) Correspondingly,%huscans for anunsigned shortand%hhufor anunsigned char. -
%f: Scan a floating-point number in normal (stock-still-point) notation. -
%chiliad,%G: Scan a floating-point number in either normal or exponential notation.%guses lower-case letters and%Guses upper-case. -
%x,%X: Scan an integer as an unsigned hexadecimal number. -
%o: Scan an integer every bit an octal number. -
%due south: Scan a character string. The scan terminates at whitespace. A zilch graphic symbol is stored at the end of the string, which means that the buffer supplied must exist at least 1 grapheme longer than the specified input length. -
%c: Scan a character (char). No null grapheme is added. -
(space): Space scans for whitespace characters. -
%lf: Scan as a double floating-point number. -
%Lf: Scan as a long double floating-point number.
The in a higher place can exist used in chemical compound with numeric modifiers and the l, L modifiers which stand for "long" in between the percent symbol and the letter of the alphabet. There tin also be numeric values between the percent symbol and the letters, preceding the long modifiers if any, that specifies the number of characters to be scanned. An optional asterisk (*) right after the percent symbol denotes that the datum read past this format specifier is non to be stored in a variable. No argument backside the format cord should be included for this dropped variable.
The ff modifier in printf is non present in scanf, causing differences between modes of input and output. The ll and hh modifiers are not nowadays in the C90 standard, but are nowadays in the C99 standard.[1]
An instance of a format cord is
-
"%7d%s %c%lf"
The higher up format string scans the first seven characters every bit a decimal integer, then reads the remaining as a string until a infinite, new line or tab is found, and then scans the offset non-whitespace character following and a double-precision floating-point number afterwards.
Error handling [edit | edit source]
scanf is usually used in situations when the program cannot guarantee that the input is in the expected format. Therefore a robust program must cheque whether the scanf telephone call succeeded and take appropriate action. If the input was non in the right format, the erroneous information will still be on the input stream and must be read and discarded before new input can be read. An culling method of reading input, which avoids this, is to use fgets and and so examine the cord read in. The last step can be done by sscanf, for case.
Security [edit | edit source]
Like printf, scanf is vulnerable to format cord attacks. Bang-up care should exist taken to ensure that the formatting string includes limitations for string and array sizes. In nearly cases the input string size from a user is arbitrary; information technology can not exist determined before the scanf function is executed. This means that uses of %s placeholders without length specifiers are inherently insecure and exploitable for buffer overflows. Another potential problem is to permit dynamic formatting strings, for example formatting strings stored in configuration files or other user controlled files. In this case the immune input length of cord sizes tin can not be specified unless the formatting string is checked beforehand and limitations are enforced. Related to this are additional or mismatched formatting placeholders which do not lucifer the actual vararg listing. These placeholders might be partially extracted from the stack, contain undesirable or fifty-fifty insecure pointers depending on the particular implementation of varargs.
/*Another employ that works but on some special compilers is:
scanf("Please enter a value %d",&north);
Which prints the string in quotes and stops to accept input at the indicated %signs.*/
Come across likewise [edit | edit source]
-
printf - C programming language
- C++
- PHP
- Format string set on
External links [edit | edit source]
- : input format conversion – Linux Library Functions Manual
- C++ reference for
std::scanf
- ↑ C99 standard, §vii.19.vi.2 "The fscanf function" alinea eleven.
guzmancomillonall.blogspot.com
Source: https://en.wikibooks.org/wiki/C_Programming/stdio.h/scanf
0 Response to "How to Read a Number in C Using Sscanf and Fgets"
Enregistrer un commentaire