Handling Simple C Input & Output

Entering and Displaying Data... In C

    Introduction

    The main purpose of any program is the ability to be interactive for the user. As it would be useful for the user to define data values. To achieve this, we need to use input/output capabilities. The functions we will use to allow the user to interact would be scanf, which like printf, is defined as a method in stdio.h. In this example, we will write a program which will allow a user to enter their name and age, then display the data in the correct format.

    Example Code In Detail

    Most of the functions we use in our 'Hello World' example will apply, but there will be a few new features to allow input. First, we need to set up a device to input data, as we begin with setting up two buffers, one to handle the name string, and the other which will handle the age number.

    The name buffer will be the first item declared in this program; it will be given the name user_name, as this is a simple char array string. The char buffer will allocate 50 array characters, so you cannot enter a string longer than the allocated amount declared below.

    	char user_name[50];
    	int user_age;
    

    The next item we are declaring will be the user_age variable, which we will use the int (Integer, to make things easier) data type as it will be a number (logical). This only permits fixed point numeric data to be entered. Both user_name and user_age, have not yet been assigned any data values. That is because we are going to need them empty for us to collect the data from the end user.

    	printf("What is your Name? ");
    	scanf("%s",&user_name);
    

    Ad you can see in the above example, we are using the familiar printf to print a string to ask the user's name. The next line is using a more unfamiliar function to what we have used up to now which is scanf, which is used to get any input entered. Scanf is a function, which is found in the same place as printf (stdio.h), as printf deals with output, scanf handles pure input. We need to read the input, so scanf is a logical function to call; this function works in a very ingenious way. In the first parameter argument, you can see a string "%s", tells scanf which format of input we are reading, in this case a string; hence the "%s" defined. This type of definition entered into scanf is called a format specifier, which is a ingenious command string which helps you with using this function. A format specifier can be used for different types of data. It consists of a percent sign ('%'), and then a letter specifying the type of data variable you will be using as in this case (%s) a string. It not only can be used for scanf, it can also be used for printf and plenty of other C input/output functions. The table below shows some of the different values and letters used for the format specifiers.

    Character Data Type Description
    d (D) Int Integer or any Decimal Number
    i (I) Int Integer or any Decimal Number
    u (U) Unsigned Int Unsigned Integer or any Unsigned Decimal Number (Min Number 0)
    x (X) Unsigned Int Unsigned Integer in it's Hexadecimal Value
    f float Floating Point Value
    c char Single Character
    s char* Char Array String

    The second parameter we use in the scanf we are using to get the name is the user_name char string buffer defined earlier. You can see it uses the ampersand (&) operator in front of the variable (e.g. &user_name). That is because the scanf requires the memory address, which will store the entered data to the variable via the address. The importance of ampersands will be more clear as we go through these tutorials. It is best advised when using scanf, use the ampersand, or it will most likely have undesired effects (meaning it will not work!)

    Now we know how to handle format specifiers, we will now move onto entering the age.

    	printf("\nWhat is your age? ");
    	scanf("%d",&user_age);
    

    Nearly same as before, the only difference is that the format specifiers will use '%d', as we are this time using an integer (int).

    	printf("\nHello User, your name is %s, and your age is %d",user_name,user_age);
    

    Once the user entered their values, we will output the data in a string. As you can see in the example directly above, printf has more parameter arguments than what we have seen or used previously. That is because we are using variable data to output. In the second and third parameters, we have placed user_name and user_age respectively. You can place as many variables in as many parameters that you may need to use in a string (Been careful, of course!). In this case, we only need the two. In the first parameter string, you can see format specifiers; %s will be where the user_name string variable will be placed, and user_age will be placed where %d is. Make sure you keep the format specifier values in the same order as the variables data types you have passed through the parameters (e.g. ("%s %f %d", (char*(string)),(float),(int))).

    In printf, just think of format specifiers you will use as a placeholder, where the output data will be slotted in.

    	fflush(stdin);
    
    	while(getchar() != '\n');
    

    Summary

    Once we have finished, we need to close the programs appropriately, instead of abruptly. So after the string has come on display, it is important to clean the input that we have entered. So we will use the fflush function. Fflush is there to totally clean out the input buffer, so any data does not stay on the system. The parameter uses the variable stdin, which means input. Once that is done, we wait in a while loop. In this while loop, we will wait until an end of line, or Return/Enter key is entered. Once the Enter key is the program will close straight away.

    Important Note

    Important Note - Visual Studio - In the build you we be receive warnings which will inform you that you are using deprecated functions such as scanf. There's nothing wrong with the code, it's a Microsoft Visual Studio configuration set up task for you to fix, which is easy. I have already amended it inside the solution project. But just in-case, you create your own project and you are not aware. Go into Project > Properties, then once you have opened the Properties window, select on the left hand side Configuration Properties > C/C++ > Preprocessor. On your right, once you have reached the destination, on your right, you can see the first item on the menu Preprocessor Definitions. Select and edit at the end of the string and place _CRT_SECURE_NO_WARNINGS. Then you will not receive the warning again for that specific problem.

    /*
    	ENTER DETAILS	ReliantCode
    	Input Details, then the program outputs the Data
    */
    
    #include <stdio.h>
    
    int main()
    {
    	char user_name[50];
    	int user_age;
    
    	printf("What is your Name? ");
    	scanf("%s",&user_name);
    
    	printf("\nWhat is your age? ");
    	scanf("%d",&user_age);
    
    	printf("\nHello User, your name is %s, and your age is %d",user_name,user_age);
    	fflush(stdin);
    
    	while(getchar() != '\n');
    	return 0;
    }
    	
    blog comments powered by Disqus
    Download Files Here

    PDF Version Here

    Download this Article in PDF

    Feedback on Article

    Report Bugs, Errors or Send Feedback

    MD5 Hash Check : What is MD5?