Writing Strings to Screen


Using printf Function

We've made extensive use of the printf function with the %s format for printing strings on screen. The format %s can be used to display an array of characters ending in null. For example, statements

printf("%s", name);

The name of the array can be used to display the full content.

We can also specify the subtlety that the array displays. For example, the specification


%10.4

indicates that the first four characters are to be printed in a field width of 10 columns.

However, if we include the minus sign in the specification, the string will be printed left-justified.


Using putchar and puts Functions

Like getchar, C supports another character handling function putchar to output the values of character variables. It takes the following form :

char ch = 'a';
    putchar(ch);

The function putchar requires one paramter. This statement is equivalent to :

printf("%c",ch);

char name[6] = "India";
    for(int i=0;i<6;i++)
    putchar(name[i]);
   putchar('\n');
   

Another and more convenient way of printing string values is to use the function puts declared in the header file . This is a one parameter function and invoked as under :

puts(str);

Where str is a string variable where the value of the string is. It prints the value of the string variable and then moves the cursor to the beginning of the next line of the screen. For example, the program section

char line[100];
    gets(line);
    puts(line);
    

Reads a line of text from the keyboard and displays it on the screen. Note that the syntax is much easier to use than the scanf and printof statements.