Computer Science
scanf in C
scanf is a function in the C programming language that reads input from the standard input stream and stores it in variables. It is commonly used to read user input from the keyboard and assign it to variables for further processing in a program. The function uses format specifiers to determine the type of input being read.
Written by Perlego with AI-assistance
Related key terms
1 of 5
8 Key excerpts on "scanf in C"
- Martin Oliver Steinhauser(Author)
- 2012(Publication Date)
- De Gruyter(Publisher)
In a way, this function is the complement of printf() , see Section 2.2.6 on Page 117. The data stream is read from (stdin), which usually is the keyboard. scanf() – like printf() – is declared in the header file , which is why you have to include this header file, as in Listing 14. When you run this program, you are asked in line 7 to enter an integer. 25 In pure C++ these functions could easily be generalized to return whatever types of real , complex , or integer variables through the use of classes and templates. Section 2.2 First steps in C 123 Listing 13. Use of predefined macros. (*) 1 #include 2 #include 3 4 #if defined ( __STDC_VERSION__ )&& __STDC__VERSION >= 199901 L 5 void function( void ) { 6 printf ( Name of t h i s f u n c t i o n : %s n , __func__) 7 } 8 #else 9 void function( void ) { 10 printf ( No C99 s t a n d a r d c o m p i l e r n ); 11 } 12 #endif 13 14 int main ( void ) { 15 #ifdef __STDC__ 16 printf ( Using an ANSI C c o m p i l e r n ); 17 #endif 18 printf ( Date of c o m p i l a t i o n : %s n , __DATE__); 19 printf ( Time of c o m p i l a t i o n : %s n , __TIME__); 20 21 printf ( Line : %3d | F i l e : %s n , __LINE__ , __FILE__ ); 22 #line 99 f i l e . c /* sets the line number and the file name */ 23 printf ( Line : %3d | F i l e : %s n , __LINE__ , __FILE__ ); 24 function (); 25 return EXIT_SUCCESS ; 26 } Listing 14. Example for the use of the C scanf() function. 1 /* Usage of scanf () */ 2 #include 3 4 int main ( int argc , char *argv []) 5 { 6 int var; 7 printf ( P l e a s e e n t e r an i n t e g e r : ); 8 scanf ( %d , &var); 9 printf ( You e n t e r e d %d n , var); 10 return (0); 11 } scanf() in line 8 awaits your input, which you have to verify by pressing the return key. Then the input value is assigned to the integer variable var in line 8 and printed in line 9. The screen output when running Listing 14 is: Please enter an integer: 34567 You entered 34567- eBook - ePub
Learn C Programming
A beginner's guide to learning C programming the easy and disciplined way
- Jeff Szuhay(Author)
- 2020(Publication Date)
- Packt Publishing(Publisher)
to limit possible input characters section.- printf() allows the field width and precision to be specified with the * and arguments; scanf() uses * for a completely different purpose—to suppress assignment. For instance, using * allows us to skip over an input value, if needed.
One final difference between printf() and scanf() is that in the input strings to scanf(), whitespace is critical in the process of parsing the input strings into values. We will explore this behavior next.Reading numerical input with scanf()
To begin our exploration of scanf(), we begin by reading an integer and a double from the console. Rather than attempt to explain how scanf() interprets the input, I believe it would be far better to first get an intuitive experience of how it works. We begin with the following program:#include <stdio.h>int main( void ) {int anInteger = -1;doubleaDouble = -1.0;printf( "Enter an integer and a decimal number: " );scanf( "%d%lf" , &anInteger , &aDouble ); printf( "1. integer:%d\n" , anInteger );printf( "2.double:%lf\n" , aDouble ); }This simple program first initializes values that will be used to store input. If scanf() can't assign values, we will see these default values. We will use two simple numbers for now. However, as we will see, if the user enters these numbers, we will be unable to tell whether they are default values that were not assigned by scanf() or whether the user actually entered these numbers.The program then prints a prompt for the user to enter an integer and a decimal number. It then reads what is entered using scanf()and tries to assign values to the two variables. The last two statements print the values of the two variables. The essential work of this program takes place in the single scanf() statement. Notice that even though there is no space between %d and %lf, whitespace remains an important consideration for input. - No longer available |Learn more
C Programming
A Self-Teaching Introduction
- Rajiv Chopra(Author)
- 2017(Publication Date)
- Mercury Learning and Information(Publisher)
Under this category, the scanf( ) function is used to read values from the keyboard while the printf( ) function is used to display values on the output terminal. Both of these func- tions are defined in the header file. The scanf( ) function is used to accept input data from a standard device in a fixed format. Its syntax is as follows: Syntax scanf(“format string”, arguments); where format string contains format specifiers which begin with the ‘%’ character, listed as follows: Format Specifier Input Types Data Type %d or %i %u %ld %lu %x %o Short signed integer INTEGER Short unsigned integer Long signed integer Long unsigned integer Unsigned hexadecimal integer Unsigned octal integer %f %lf Single precision float FLOAT Double precision float %c Signed character CHARACTER Unsigned character %s String STRING Arguments specify where the input data is to be stored while receiving it from a standard input device. There must be an argument for each input da- tum. Extra arguments are ignored; if there are too few arguments, the results become unpredictable. The arguments to the scanf function are point- ers. This is the reason why arguments are preceded by an ampersand (&) symbol (i.e., an address operator). The & operator assigns it a memory location. Also note that the order of these specifiers and their arguments must be the same or else an error is reported by the C compiler. 44 • C PROGRAMMING Next let us discuss the printf( ) function. The printf( ) function is used to accept output data from a computer to a standard device in a fixed format. It is a formatted output function. Its syntax is as follows: Syntax printf(“format string”, arguments); For example, printf(“My name is Dr. Rajiv”); /* double quotes are used */ For another example, printf (“%d”, a); Also note that here the value of ‘a’ is inserted at the ‘%d’ position and thus the value of ‘a’ gets printed. - eBook - ePub
- Jeff Szuhay(Author)
- 2022(Publication Date)
- Packt Publishing(Publisher)
Using a scan set to limit possible input characters section.- printf() allows the field width and precision to be specified with the * and arguments; scanf() uses * for a completely different purpose—to suppress assignment. For instance, using * allows us to skip over an input value if needed.
One final difference between printf() and scanf() is that in the input strings to scanf() , whitespace is critical in the process of parsing the input strings into values. We will explore this behavior next.Reading numerical input with scanf()
To begin our exploration of scanf() , we begin by reading an integer and a double from the console. Rather than attempt to explain how scanf() interprets the input, I believe it would be far better to first see an example of how it works. We begin with the following program:#include <stdio.h> int main( void ) { int anInteger = -1; double aDouble = -1.0; printf( "Enter an integer and a decimal number: " );scanf( "%d%lf" , &anInteger , &aDouble );printf( "1. integer: %d\n" , anInteger ); printf( "2. double: %lf\n" , aDouble ); return 0; }This simple program first initializes values that will be used to store input. If scanf() can't assign values, we will see these default values. We will use two simple numbers for now. However, as we will see, if the user enters these numbers, we will be unable to tell whether they are default values that were not assigned by scanf() or whether the user actually entered these numbers.The program then prints a prompt for the user to enter an integer and a decimal number. It then reads what is entered using scanf() and tries to assign values to the two variables. The last two statements print the values of the two variables. The essential work of this program takes place in the single scanf() statement. Notice that even though there is no space between %d and %lf - eBook - PDF
- Xingni Zhou, Qiguang Miao, Lei Feng(Authors)
- 2020(Publication Date)
- De Gruyter(Publisher)
158 4 Input/output [Analysis] When using scanf to read character sequences, we should note that a single scanf cannot read the entire sequence if there are spaces in it. The input in this example is hello □ world. Because %s stops reading at spaces, only hello is stored into array str while world is not. Note how it is different from using gets function to read strings. Think and discuss How to find errors in scanf input quickly? We have seen in these examples that data are often read incorrectly when reading input with scanf. Is it possible to find errors without tracing in debuggers or printing out all input? Discussion: In fact, scanf function provides a mechanism to check the correctness of input argu-ments. Basically, it can tell its caller the number of correct inputs. If all inputs are wrong, scanf will return 0. If we press Ctrl+z to exit, scanf will return -1 (which is character literal EOF). The function signature of scanf is as follows: int scanf(format control sequence, address 1, address 2, … address n); A test program is given in the following example. Example 4.15 Return value of scanf function Examine the correctness of input data using the return value of scanf function. [Analysis] 1. Test program We use an integer count to store the return value of scanf . The program is as follows: #include int main(void) { int a,b,c; int count; printf(Enter values of a, b and c, separated by spacen); count=scanf(%d%d%d,&a,&b,&c); printf(a=%d,b=%d,c=%d,count=%dn,a,b,c,count); return 0; } 4.3 Data input 159 2. Test result The test result is given in Figure 4.31. The value of count indicates the number of data that are correctly read. If we don ’ t want to enter anything, we can press Ctrl + Z to exit. - eBook - PDF
- Kunal Pimparkhede(Author)
- 2017(Publication Date)
- Cambridge University Press(Publisher)
56 ✦ Computer Programming with C++ This will obviously not be an issue if this scanf() statement is the very first input statement in the program but it is always better to keep a habit to put a SPACE before each of the format specifiers to avoid scanning of incorrect inputs. Notes Always ensure that there is a SPACE before %c in the control string while reading character input using scanf() . All the other format specifiers such as %d,%f,and %ld (including %s which is for strings) skip the new line and spaces at input and hence it is not necessary to put a space before them in the control string. But it is always a better programming practice to separate the format specifiers within the control string of scanf() function by space as it improves the overall readability of the statement. 2.9.1 Delimited input using scanf() It is possible to use any other delimiter apart from space in the control string of scanf() . For example, consider three variables a, b, and c declared as below int a,b,c; The statement, scanf(%d$%d$%d$,&a,&b,&c); has a symbol $ in the control string which acts as an separator between two format specifiers. Hence, it is the responsibility of the user to input data which is $ separated . This means that after entering each input value, user must enter a $ symbol as shown below 10$20$30$ After typing this input when the user hits an ENTER key, the scanf() statement will store 10 in variable a, 20 in variable b, and 30 in variable c . If user fails to enter $ and inputs data in any other format, the scanf() will crash. Remember when we put $ as a separator in format specifiers, it actually informs scanf() to skip $ in the input string and hence variables a, b, and c are correctly initialized to 10, 20, and 30, respectively. This feature is rarely used in programs because there is a risk that scanf() will crash if the user does not input data exactly in the same format as needed by scanf() . - eBook - ePub
Scientific Programming: C-language, Algorithms And Models In Science
C-Language, Algorithms and Models in Science
- Luciano Maria Barone, Enzo Marinari, Giovanni Organtini, Federico Ricci Tersenghi(Authors)
- 2013(Publication Date)
- WSPC(Publisher)
exp1 could be either a simple variable or a complex expression since we could have written printf("Value in degrees Celsius = %f",(tf - offset) * conv); i.e., we could have computed the value of tc directly in the arguments of printf. The format specifier %f refers to a quantity which is represented in floating-point format. In Table 3.7 the most frequently used format specifiers are listed for printf.Table 3.7 Output format specifiers.The scanf function, on line 6 of Listing 3.4, serves to read the value of one or more input variables (for instance from the keyboard). Its format is similar to that of the printf function. However, there are some important differences between the two. A first difference is that in the scanf function only format specifiers of the variables which are to be acquired can be included between the double quotes "···". A second difference is the presence of the & symbol in the scanf function which must preceed every such variable.The general syntax of the scanf statement isThe character string enclosed between double quotes "···" contains all format specifiers of the variables which are to be acquired in var1, var2,...and only those. Also in this case, the number of variables which follow the character string are not fixed and each variable must be preceded by the < character. On line 6 of Listing 3.4 the format specifier %lf for the double type variable tf is used. Note that if a format specifier %f corresponding to the float type were used, the program would behave differently. In Table 3.8 we list the most frequently used format specifiers for reading purposes.Table 3.8 Input format specifiers. The I/O functions for files are discussed in Chapter 6.Finally, let us underline that the program Listing 3.4 actually does not compile correctly2 ; The reason is connected to the considerations made in Section 2.4, i.e. the necessity to link the code written by the pro-grammer (Listing 3.4) to the already existing code, which in this case concerns the code for the printf and scanf functions. Indeed, the I/O functions printf and scanf are not written by the person who encodes a program to solve a given problem; rather they are already available from the C compiler, which is why they are generally called system functions. - eBook - PDF
- Subrata Saha, Subhodip Mukherjee(Authors)
- 2017(Publication Date)
- Cambridge University Press(Publisher)
But the most convenient way to string input is to use gets( ) function. This function is defined at stdio.h file. Using this function we can take multiword string input also as it terminates reading on encounter of new line character(‘n’). The general form of gets( ) : gets( array_name); Following program shows the use of gets( ) function. P ROGRAM : 12.11 void main() { char nm[40]; printf(“Enter a name: ”); gets(nm); printf(“The name is: %s”, nm); } Sample Output Enter a name: Subrata Saha The name is: Subrata Saha Here is a sample program that will demonstrate how we can declare, store and access a string. Basic Computation and Programming with C 278 P ROGRAM 12.12 Program to count the number of characters in a string. #include #include void main() { char string[100]; int i=0; puts(“Enter Any String : ”); gets(string); while( string[i] != ‘0’) { i++; } printf(“nTotal number of characters in the string ”%s” is %d”, string, i); } Sample Output Enter Any String: This is a sample string. Total number of characters in the string “This is a sample string.” is 24. In the above program, first we take the input using gets( ). Then each character of the string is checked and counted. When the ‘0’ is encountered, the while loop is terminated. 12.3 sscanf( ) AND sprintf( ) FUNCTION The sscanf() and sprintf() are two special versions of printf() and scanf() statement used to handle string in a different approach. These two functions are mainly used in file handling. The utility and usage of sscanf() and sprintf() are explained below: 12.3.1 sscanf() Function sscanf() function is used for formatted string read purpose. It helps to extract strings from a given string. It implies that the data is to be taken out from the character array according to the conversion specifier and stored them into respective variables. A terminating null character is automatically appended after the content.
Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.







