You are on page 1of 42

C program to read string with spaces using scanf() function

Read string with spaces using scanf() function in C programming language - In this program we are going to
explain how we can take input of a string with spaces?

Let’s see what happened, when we read a string like another type of input

#include <stdio.h>
int main()
{
char name[30];
printf("Enter name: ");
scanf("%s",name);

printf("Name is: %s\n",name);


return 0;
}

Output -1 (Enter name without space)

Enter name: Alex


Name is: Alex

Output -2 (Enter name with space)

Enter name: Alex Thomas


Name is: Alex

In both cases variable name stored only "Alex"; so, this is clear if we read a string by using "%s" format specifier,
string will be terminated when white space found.

How to read string with spaces in C?


1) Read string with spaces by using "%[^\n]" format specifier

The format specifier "%[^\n]" tells to the compiler that read the characters until "\n" is not found.

Consider the program

#include <stdio.h>
int main()
{
char name[30];
printf("Enter name: ");
scanf("%[^\n]",name);

printf("Name is: %s\n",name);


return 0;
}

Output
Enter name: Alex Thomas
Name is: Alex Thomas

See the output, now program is able to read complete string with white space.

Problem -1 [Read string after integer input]

Here, we will read the person age then name and see what will happen? (i.e. we are reading the string after integer
input)

Consider the program

#include <stdio.h>
int main()
{
int age;
char name[30];

printf("Enter age: ");


scanf("%d",&age);
printf("Enter name: ");
scanf("%[^\n]",name);

printf("Name is: %s, age is: %d\n",name,age);


return 0;
}

Output

Enter age: 23
Enter name: Name is: , age is: 23

Oh nooooooooooooooo!

The age input was successful but compiler doesn’t wait to readname and moves to next statement which
was printf("Name is: %s, age is: %d\n",name,age); and the output is "Enter name: Name is: , age is:
23" which we didn’t expect.

Why this happened?

As we enter an integer value and hit enter to read next value, compiler stores either enter or null into the string’s
first character and string input terminates.

Here is the proof?

Here we are printing the value of string’s first character by using printf("Name is: %d, age is:
%d\n",name[0],age); the output will be "Enter name: Name is: 0, age is: 23"
Consider the program

#include <stdio.h>
int main()
{
int age;
char name[30];

printf("Enter age: ");


scanf("%d",&age);
printf("Enter name: ");
scanf("%[^\n]",name);

printf("Name is: %d, age is: %d\n",name[0],age);


return 0;
}

Output

Enter age: 23
Enter name: Name is: 0, age is: 23

Here compiler stores, null (0) to the string’s first character that is name[0]

How to fix it?

We have to read a character from input buffer and store it into temporary variable (remember - if we are going to
read string or character after an integer or float (in some cases) input then we should read a temporary character
which may available in the input buffer)

I am using a statement scanf("%c",&temp); before reading the string (which is going to be read after an integer
input).

Consider the program

#include <stdio.h>
int main()
{
int age;
char name[30];
char temp;

printf("Enter age: ");


scanf("%d",&age);
printf("Enter name: ");
scanf("%c",&temp); // temp statement to clear buffer
scanf("%[^\n]",name);

printf("Name is: %s, age is: %d\n",name,age);


return 0;
}

Output
Enter age: 23
Enter name: Alex Thomas
Name is: Alex Thomas, age is: 23

See, now we are able to read complete string (with spaces) after taking an integer input.

Another way to read string with spaces in C


Using fgets()

fgets() function requires three parameters

 char *s - character pointer (in which string will be stored)


 int n - maximum number of character of the string
 FILE *stream – a pointer of file stream, we can use “stdin”

fgets() will reads the complete string with spaces and also add a new line character after the string input.

Consider the program

#include <stdio.h>
int main()
{
int age;
char name[30];
char temp;

printf("Enter age: ");


scanf("%d",&age);
printf("Enter name: ");
scanf("%c",&temp); // temp statement to clear buffer
fgets(name,30,stdin);

printf("Name is: %s, age is: %d\n",name,age);


return 0;
}

Output

Enter age: 23
Enter name: Alex Thomas
Name is: Alex Thomas
, age is: 23

printf() statement within another printf() statement in C


Here, we are going to learn how to use and evaluate printf() statement within another printf() statement in C
programming language?
Submitted by IncludeHelp, on September 13, 2018

A printf() function is a standard library function, that is used to print the text and value on the standard output
screen. Here, we will evaluate the expression – where a printf() is used within another printf() statement.
Consider the statement:

printf ("%d", printf ("Hello"));

Note these points:

1. printf() prints the text as well as the value of the variable, constant etc.
2. printf() returns an integer value that is the total number of printed characters including spaces, carriage
return, line feed etc.

Evaluation of the above written statement:

printf() function evaluates from right to left, thus printf("Hello") will be evaluated first, that will
print "Hello"and printf("Hello") will return the total number of printed character that is 5 and then the output of
this printf("Hello") after printing "Hello" will be 5.

Thus, finally, the output of the above-written statement will be: "Hello5".

Example:

#include <stdio.h>

int main(void)
{
printf("%d", printf ("Hello"));
return 0;
}

Output

Hello5

Using more than one printf() within printf() statement


Consider the following statement:

printf ("%d%d", printf ("Hello") , printf ("friends"));

Evaluation:

As we said above that the printf() arguments evaluates from right to left, thus, printf("Friends") will be
evaluated first and return 7, after that statement printf("Hello") will be evaluated and return 5. Thus, the final
output will be "friendsHello57".

Example:

#include <stdio.h>

int main(void)
{
printf ("%d%d", printf ("Hello"), printf ("Friends"));
return 0;
}

Output

FriendsHello57

Difference between printf and puts in c programming language


In this tutorial we will learn what are the differences between printf and puts functions in c programming
language?

Both functions are declared in stdio.h and used to send text/character stream to output stream (that will print on
the standard output device).

But both are not same, their functionality, syntaxes and usages are different; basically they have two differences:

1. printf can print the value of mixed type of variables but puts can’t
print, puts has single parameter that is character array (character pointer).
2. printf prints whatever you provide, it may be text, text + values etc without
adding new line after the text while puts add one more character that is new
line character (\n) just after the text/character stream.

So basically, if we want to print the string either we can use printf or puts, but if we want to add new line after the
string, we should use puts.

printf
As we discussed in many posts that printf is used to print message/text/character stream along with the values of
variables.

More about printf Read - Difference between printf and sprintf in c programming language.

puts
puts is used to print the string (character stream) on the output stream (that will print on the standard output device)
with additional new line character (\n).

Here is the syntax

int puts(const char *text);

Here,

 text is the character stream to be printed, it may be direct value within the
double quotes or a character array variable.
 Return type int - puts returns total number of printed characters excluding new
line character (which adds automatically).

Here are three variations of puts

puts("Hello world!");
char msg[]="Hello world!";
puts(msg);
const char *msg="Hello world!";
puts(msg);

Consider the following program - how printf and puts printing the values?
#include <stdio.h>

int main(){

printf("Using printf...\n");
printf("This is line 1.");
printf("This is line 2.");

printf("\n\n");
printf("Using puts...\n");
puts("This is line 1.");
puts("This is line 2.");

printf("End of main...\n");

return 0;
}

Output

Using printf...
This is line 1.This is line 2.

Using puts...
This is line 1.
This is line 2.
End of main...

When "This is line 1." "This is line 2." are printing through printf both strings are printing in same line, while
strings are printing through puts both strings are printing in separate line due to puts feature [Adds additional
character new line after the string].

Difference between printf and sprintf in c programming


language
Here we are going to learn about printf and sprintfstatements in c programming language, when and how they
are used? What are their parameters and what they return?

printf
printf is used to print text (string/ character stream) or/and values on standard output device.

Here is the syntax

int printf(const char *format, ...);

Here,

 format provides the format of the text string which is going to print on the
output device with the help of format specifiers like %s, %d, %f etc.
 ... provides the list of arguments to be print.
 Return type int returns total number of printed characters on the output screen.

A simple program to print "Hello"


#include <stdio.h>

int main()
{
printf("Hello");

return 0;
}

Output

Hello

Program to print Name and Age


#include <stdio.h>

int main()
{
printf("My name is %s, I am %d years old\n","Mike",23);

return 0;
}

Output

My name is Mike, I am 23 years old

Program to get and print return value of printf


#include <stdio.h>

int main()
{
int n;

n=printf("Hello world!");

printf("\nTotal number of printed characters are: %d\n",n);

return 0;
}

Output

Hello world!
Total number of printed characters are: 12

sprintf
sprintf is used to send (copy) formatted text (string/ character stream) to a string.

Here is the syntax

int sprintf(char *str, const char *format,...);

Here,

 char *str - Is character array in which formatted text will be sent (copied).
 format provides the formatted text with the help of format specifiers.
 ... provides the list of arguments to be print.
 Return type int returns total number of copied (sent) characters into the char
*str.

A simple program to copy Name, age with formatted text in a character array
#include <stdio.h>

int main()
{
char str[100];

sprintf((char*)str,"My name is %s, I am %d years old.","Mike",23);

printf("Text is: %s\n",str);

return 0;
}

Output

Text is: My name is Mike, I am 23 years old.

A program to get and print return value of sprintf


#include <stdio.h>

int main()
{
char str[100];
int n;

n=sprintf((char*)str,"My name is %s, I am %d years old.","Mike",23);

printf("Text is: %s\n",str);


printf("Total number of copied characters are: %d\n",n);

return 0;
}

Output

Text is: My name is Mike, I am 23 years old.


Total number of copied characters are: 35

Difference between %d and %i format specifier in C


programming language.
Format specifier/ conversion characters

In c programming language, there are some set of characters preceded by % character, which define the type of
input and output values, know as format specifiers/ conversion characters.

For example - if you want to read and print single character using scanf and printf function, %c is used.

Consider the following statements

char gender;
scanf("%c",&gender);
printf("Gender is: %c\n",gender);

Here %c is using in both statements scanf and printf, while reading values from the user, %c in scanf define that
single character is going to be read, similarly %c in printf defines that only single character will be printed.

Difference between %d and %i format specifier?


%d and %i both are used to read and print integer values, still they have differences.

%d - Specifies signed decimal integer

%i - Specifies integer

%d and %i as output specifiers

Both specifiers are same if they are using as output specifiers, printf function will print the same value
either %d or %i is used.

Consider the following example

#include <stdio.h>

int main()
{
int a=6734;
printf("value of \"a\" using %%d is= %d\n",a);
printf("value of \"a\" using %%i is= %i\n",a);
return 0;
}
value of "a" using %d is= 6734
value of "a" using %i is= 6734

%d and %i as Input specifiers

Both specifiers are different if they are using as input specifiers, scanf function will act differently based
on %d and %i.

%d as input specifier

%d takes integer value as signed decimal integer i.e. it takes negative values along with positive values but values
should be decimal.

%i as input specifier

%i takes integer value as integer value with decimal, hexadecimal or octal type.

To give value in hexadecimal format - value should be provided by preceding "0x" and value in octal format - value
should be provided by preceding "0".

Consider the following example

#include <stdio.h>

int main()
{
int a=0;
int b=0;

printf("Enter value of a: ");


scanf("%d",&a);

printf("Enter value of b: ");


scanf("%i",&b);

printf("a=%d, b=%d\n",a,b);

return 0;
}
Enter value of a: 2550
Enter value of b: 0x2550
a=2550, b=9552

In this example the entered value of a is 2550 (through %dformat specifier) and the entered value of b is 0x2550
(through %i format specifier). Since 0x2550 is given to b which is scanning value through %i so it would be 9552
(which is the decimal value of 0x2550).

Single Character Input and Output using getch(), getche(),


getchar(), putchar() and putch()
getch()

This function is used to get (read) single character from standard input device (keyboard) without echoing i.e. it does
not display the input character & it does not require [return] key after input. getch() is declared in conio.h header
file.

/*Compatible for TurboC compiler */


#include <stdio.h>
#include <conio.h>

int main()
{
char ch;

printf("Enter a character :");


ch=getch();

printf("\nEntered character is : %c",ch);


return 0;
}

Output

Enter a character:
Entered character is: G

Here, input character is G, which is not display while giving input.

getche()

This function is used to get (read) single character from standard input device (keyboard) with echoing i.e. it displays
the input character & it does not require [return] key after input. getche() is declared in conio.h header file.

/*Compatible for TurboC compiler */


#include <stdio.h>
#include <conio.h>

int main()
{
char ch;
printf("Enter a character :");

ch=getche();
printf("\nEntered character is : %c",ch);

return 0;
}

Output

Enter a character: G
Entered character is: G

Here, input character is G, which displays character while giving input and does not require [return] after pressing ‘G’.
getchar()

This function is used to get (read) single character from standard input device (keyboard) with echoing i.e. it displays
the input character & require [return] key after input. getchar() is declared in stdio.h header file.

#include <stdio.h>

int main()
{
char ch;

printf("Enter a character :");


ch=getchar();
printf("\nEntered character is : %c",ch);

return 0;
}

Output

Enter a character: G
Entered character is: G

Here, input character is G, which displays character while giving input and after pressing [return] key, program’s
execution will move to next statement.

putchar() & putch()

These functions are used to put (print) a single character on standard output device (monitor).

#include <stdio.h>
int main()
{
char ch;

printf("Enter a character :");


ch=getchar();
printf("\nEntered character is :");
putchar(ch);

return 0;
}

Output

Enter a character: G
Entered character is: G

Formatted Input & Output using printf() and scanf()


printf()
This function is used to print text as well as value of the variables on the standard output device (monitor), printf is
very basic library function in c language that is declared in stdio.h header file.

Syntax:

printf(“message”);

printf(“message + format-specifier”,variable-list);

First printf() style printf the simple text on the monitor, while second printf() prints the message with values of the
variable list.

#include <stdio.h>

int main()
{
printf("Message-1");
printf("Message-2");
printf("Message-3");
return 0;
}

Output

Message-1Message-2Message-3

How to print value of the variables?


To print values of the variables, you need to understand about format specifiers are the special characters followed
by % sign, which are used to print values of the variable s from variable list.

Format specifiers

Here are the list some of the format specifiers, use them in printf() & scanf() to format & print values of the variables:

Character (char) %c

Integer (int) %d

Insigned integer (unsigned int) %ld

Long (long) %ld

Unsigned long (unsigned long) %lu

Float (float) %f

Double (double) %lf

Octal Value (octal value) %o

Hexadecimal Value (hex value) %x

String (char[]) %s
**NOTE** Use ‘u’ for unsigned type modifier, ‘l’ for long.

Escape Sequences

To print special extra line/spaces etc, we use escape sequences, these characters are followed by ‘\’ (slash).

\\ \

\” “

\’ ‘

\? ?

\a Alert

\b Back space

\n New Line

\t Horizontal tab

\v Vertical tab

\r Carriage return

Consider the following examples:

#include <stdio.h>

int main()
{
int num=100;
float val=1.23f;
char sex='M';

//print values using different printf


printf("Output1:");
printf("%d",num);
printf("%f",val);
printf("%c",sex);

//print values using single printf


printf("\nOutput2:"); // \n: for new line in c
printf("%d,%f,%c",num,val,sex);
return 0;
}

Output

Output1:1001.230000M
Output2:100,1.230000,M

Padding integers with 0’s / Spaces

Another important and useful concept is padding values with 0’s or Spaces.
Padding with Space: Use %[n]d, here [n] is the number of characters, use %-[n]d for right space padding.

#include <stdio.h>
int main()
{
int a=10;
int b=1234;
int c=11111;

printf("\nLeft padded with spaces:");


printf("\na=%5d \nb=%5d \nc=%5d",a,b,c);

printf("\nRight padded with spaces:");


printf("\na=%-5d,b=%-5d,c=%-5d",a,b,c);
return 0;
}

Output

Left padded with spaces:


a= 10
b= 1234
c=11111
Right padded with spaces:
a=10 ,b=1234 ,c=11111

Padding with Zeros: Use %0[n]d, here [n] is the number of characters.
#include <stdio.h>
int main()
{
int a=10;
int b=1234;
int c=11111;

printf("\nLeft padded with 0's:");


printf("\na=%05d \nb=%05d \nc=%05d",a,b,c);
return 0;
}

Output

Left padded with 0's:


a=00010
b=01234
c=11111

Padding float values with 0’s

Consider the following examples:

#include <stdio.h>
int main()
{
float a=1.23f;
float b=1.234f;
float c=1.0f;
printf("\na=%05f \nb=%08.3f \nc=%.2f",a,b,c);
return 0;
}

Output

a=1.230000
b=0001.234
c=1.00

%05f – Since default float value prints 6 digits after precision & here is %05f, so no changes will be made.

%08.3f – “.3f” prints 3 digits after precision and “08” means padding with Zero (8 digits – including digits before and
after the precision).

%.2f – 2 Digits will print after precision.

String formatting & padding with spaces


#include <stdio.h>
int main()
{
char text1[]="includehelp";
char text2[]="includehelp.com";
char text3[]="http://www.includehelp.com";

printf("\nWithout padding:");
printf("\ntext1:%s \ntext2:%s \ntext3:%s \n",text1,text2,text3);

printf("\nWith left space padding:");


printf("\ntext1:%30s \ntext2:%30s \ntext3:%30s \n",text1,text2,text3);

printf("\nWith right space padding:");


printf("\ntext1:%-30s \ntext2:%-30s \ntext3:%-30s \n",text1,text2,text3);

return 0;
}

Output

Without padding:
text1:includehelp
text2:includehelp.com
text3:http://www.includehelp.com

With left space padding:


text1: includehelp
text2: includehelp.com
text3: http://www.includehelp.com

With right space padding:


text1:includehelp
text2:includehelp.com
text3:http://www.includehelp.com

Print value in Decimal, Octal & Hexadecimal format


You can print integer value in following formats using following format specifiers:

%d - Decimal

%o - Octal (small ‘o’)

%x - Hexadecimal (alphabets will print in small case)

%X - Hexadecimal (alphabets will print in upper case)

Consider the following example

#include <stdio.h>
int main()
{
int val=32106;

printf("\nDecimal : %d",val);
printf("\nOctal : %o",val);
printf("\nHex : %x",val);
printf("\nHex : %X",val);
return 0;
}

Output

Decimal : 32106
Octal : 76552
Hex : 7d6a
Hex : 7D6A

scanf()

This function is used to get (input) value from the keyboard. We pass format specifiers, in which format we want to
take input.

Syntax:

scanf(“format-specifier”, &var-name);

scanf(“fromat-specifier-list”, &var-name-list);

First type of scanf() takes the single value for the variable and second type of scanf() will take the multiple values for
the variable list.

Consider the following examples:

#include <stdio.h>

int main()
{

int a;
float b;
char c;
printf("Enter an integer number (value of a)?:");
scanf("%d",&a);

printf("Enter a float number (value of b)?:");


scanf("%f",&b);

printf("Enter a character (value of c)?:");


fflush(stdin); // to flush (clear) input buffer
scanf("%c",&c);

printf("\na=%d,b=%f,c=%c",a,b,c);
return 0;
}

Output

Enter an integer number (value of a)?:1234


Enter a float number (value of b)?:1.2345
Enter a character (value of c)?:G

a=1234,b=1.234500,c=G

Consider the following examples to read multiple value in single scanf statement:

#include <stdio.h>

int main()
{

int a;
float b;
char c;

printf("\nEnter value of a,b,c (an integer, a float, a character):");


scanf("%d%f%c",&a,&b,&c);

printf("\na=%d,b=%f,c=%c",a,b,c);
return 0;
}

Output

Enter value of a,b,c (an integer, a float, a character):1234 1.2345 G


a=1234,b=1.234500,c=

Here, G will not store into c variable, because we are not flushing input buffer here. So either you will have to take
input of c first or you will have to read value of c separately.

Octal and Hexadecimal Escape Sequences in C


Traditionally, an Escape Sequence starts with backsplash (\) and a single character like '\n', '\t' etc. That are used
for some specific formatting like '\n' is used set cursor at the beginning of next line and '\t' is used to set cursor
on next tab stop.
We can also use some Octal and Hexadecimal values after the backsplash, that are known as Octal and
Hexadecimal Escape Sequences.

New line using Octal and Hexadecimal Escape Sequence

"New line" or "Line feed" is a special character that has an ASCII value, The ASCII value of "New line" Escape
sequence is 10in Decimal; we can use its Octal value (12) and Hexadecimal value (0A) with backslash.

Octal Escape Sequence for New line - \012


Hexadecimal Escape Sequence for New line - \x0A

Example:

#include <stdio.h>
int main()
{
printf("Hello\012world");
printf("\n");
printf("Hello\x0Aworld");
printf("\n");
return 0;
}

Output

Hello
world
Hello
world

TAB using Octal and Hexadecimal Escape Sequence

"Tab" or "Horizontal Tab" is a special character that has an ASCII value, The ASCII value of "Tab" Escape sequence
is 9 in Decimal; we can use its Octal value (11) and Hexadecimal value (9) with backslash.

Octal Escape Sequence for New line - \011


Hexadecimal Escape Sequence for New line - \x09

Example:

#include <stdio.h>
int main()
{
printf("Hello\011world");
printf("\n");
printf("Hello\x09world");
printf("\n");
return 0;
}

Output

Hello world
Hello world

Print any character like ‘A’ using Octal and Hexadecimal Escape Sequence

By using Octal and Hexadecimal values of any character, we can print any character. For example to print ‘A’ we can
use \101(Octal Escape Sequence), or \x41 (Hexadecimal Escape Sequence).

Remember: ASCII value of 'A' in Decimal is 65, in Octal is 101and in Hexadecimal is 41.

Example:

#include <stdio.h>
int main()
{
printf("\101");
printf("%c",'\101');
printf("\n");

printf("\x41");
printf("%c",'\x41');
printf("\n");

return 0;
}

Output

AA
AA

Convert float value to string using gcvt() in C language


Learn: How to convert a float value into string using gcvt() function in C programming language?

Here, we will learn how to convert a float number (floating point value) to the string in C language?

What is gcvt()?
It's a library function of stdio.h header, this function is used to convert a floating point number to string.

Syntax:

gcvt(double value, int ndigits, char * buf);

Here,
double value : is the float/double value
int ndigits : number of digits including point (decimal point), for example if you want to get value in xx.yyy format
then it should be 6
char * buf : character pointer, in this variable string converted value will be copied.

Program to convert float value in string using gcvt() in C


#include <stdio.h>
#define MAX 50

int main()
{
float x=0.0f;
char buf[MAX];

printf("Enter first number: ");


scanf("%f",&x);

gcvt(x,6,buf);

printf("buffer is: %s\n",buf);

return 0;
}

Output

Enter first number: 123.45678


buffer is: 123.457

Difference between gets() and fgets() in C programming


language
Learn: Difference between gets() and fgets() in Cprogramming language with examples.

To read a string value with spaces, we can use either gets() or fgets() in C programming language. Here, we will
learn what is the difference between gets() and fgets() with examples?

gets()
gets() is used to read string from the standard input device until newline character not found, use of gets() may risky
because it does not check the array bound.

For example: if you have a character array with 20 characters and input is more than 20 characters, gets() will read
all characters and store them into variable. Since, gets() does not check the maximum limit of input characters, so
any time compiler may return buffer overflow error.

Consider the example:

Here, maximum number of characters are 20 and the input length is greater than 20, gets() will read and store all
characters (that's wrong and may occur buffer overflow anytime).

#include <stdio.h>
#define MAX 20

int main()
{
char buf[MAX];

printf("Enter a string: ");


gets(buf);
printf("string is: %s\n",buf);

return 0;
}

Output

Enter a string: Hi there, how are you?


string is: Hi there, how are you?

fgets()
fgets() is used to read string till newline character or maximum limit of the character array, use of fgets() is safe as
it checks the array bound.

fgets() has following parameters: buffer, maximum length, and input device reference.

Consider the example:

Here, maximum number of characters are 20 and the input length is greater than 20, fgets() will read and store only
20 characters.

#include <stdio.h>
#define MAX 20

int main()
{
char buf[MAX];

printf("Enter a string: ");


fgets(buf,MAX,stdin);
printf("string is: %s\n",buf);

return 0;
}

Output

Enter a string: Hi there, how are you?


string is: Hi there, how are y

Input an unsigned integer value using scanf() in C


Here, we are going to learn how to input an unsigned integer values using scanf() function in C programming
language?
Submitted by IncludeHelp, on September 12, 2018

Here, we have to declare an unsigned integer variable and read its value using scanf() function in C.

The data type to declare an unsigned integer is: unsigned intand the format specifier that is used
with scanf() and print() for unsigned int type of variable is "%u".
Program:

#include <stdio.h>

int main(void)
{
unsigned int value;

printf("Enter an unsigned int value: ");


scanf("%u", &value);
printf("value: %u\n", value);

//input again
printf("Enter an unsigned int value again: ");
scanf("%u", &value);
printf("value: %u\n", value);

//input again
printf("Enter an unsigned int value again: ");
scanf("%u", &value);
printf("value: %u\n", value);

return 0;
}

Output

Enter an unsigned int value: 123712


value: 123712
Enter an unsigned int value again: -1
value: 4294967295
Enter an unsigned int value again: 25501
value: 25501

Input octal value using scanf() in C


Here, we are going to learn how to input an octal value in C programming language? To read octal value, we
use "%o"format specifier in scanf() in C language.
Submitted by IncludeHelp, on September 13, 2018

Here, we have to declare an unsigned int variable and input a value which should be entered in octal format.

To input and print a value in octal format - we use "%o"format specifier.

Program:

#include <stdio.h>

int main(void)
{
unsigned int value;

printf("Input octal value: ");


scanf("%o", &value);
printf("value in octal format: %o\n", value);
printf("value in decimal format: %d\n", value);
//testing with invalid value
printf("Input octal value: ");
scanf("%o", &value);
printf("value in octal format: %o\n", value);
printf("value in decimal format: %d\n", value);

return 0;
}

Output

Input octal value: 127


value in octal format: 127
value in decimal format: 87
Input octal value: 1278
value in octal format: 127
value in decimal format: 87

Input octal value using scanf() in C


Here, we are going to learn how to input an octal value in C programming language? To read octal value, we
use "%o"format specifier in scanf() in C language.
Submitted by IncludeHelp, on September 13, 2018

Here, we have to declare an unsigned int variable and input a value which should be entered in octal format.

To input and print a value in octal format - we use "%o"format specifier.

Program:

#include <stdio.h>

int main(void)
{
unsigned int value;

printf("Input octal value: ");


scanf("%o", &value);
printf("value in octal format: %o\n", value);
printf("value in decimal format: %d\n", value);

//testing with invalid value


printf("Input octal value: ");
scanf("%o", &value);
printf("value in octal format: %o\n", value);
printf("value in decimal format: %d\n", value);

return 0;
}

Output

Input octal value: 127


value in octal format: 127
value in decimal format: 87
Input octal value: 1278
value in octal format: 127
value in decimal format: 87

Explanation:

See the second input and its result, the input value is 1278 and the accepted value is 127 because 8 is not a valid
octal digit. Octal numbers have only 8 digits which are 0, 1, 2, 3, 4, 5, 6 and 7.

Input decimal, octal and hexadecimal values in character


variables using scanf() in C
In this article, we are going to learn how to input a value in decimal, octal and hexadecimal values in a character
value using scanf() in C language?
Submitted by IncludeHelp, on September 13, 2018

Here, we will declare an unsigned char variable and input different format's value like decimal format, octal format
and hexadecimal format.

 To input and print decimal value – we use "%d" format specifier


 To input and print octal value – we use "%o" format specifier
 To input and print hexadecimal value – we use "%x"format specifier

Program:

#include <stdio.h>

int main(void)
{
//data range of unsigned char is in,
//1) decimal format 0 to 255
//2) octal format 0 to 377
//3) hexadecimal format 0 to ff

unsigned char var;


printf("Enter decimal value b/w 0 to 255: ");
scanf("%d", &var);
printf("var = %d\n", var);

printf("Enter octal value b/w 0 to 377: ");


scanf("%o", &var);
printf("var = %o\n", var);

printf("Enter hexadecimal value b/w 0 to ff: ");


scanf("%x", &var);
printf("var = %x\n", var);

return 0;
}

Output

Enter decimal value b/w 0 to 255: 198


var = 198
Enter octal value b/w 0 to 377: 172
var = 172
Enter hexadecimal value b/w 0 to ff: f9
var = f9

Input an integer value in any format (decimal, octal or


hexadecimal) using '%i' in C
Here, we are going to learn how to input an integer value in any format like decimal, octal or hexadecimal value
using '%i' format specifier in C language?
Submitted by IncludeHelp, on September 13, 2018

We know that the decimal, octal, and hexadecimal value can be read
through scanf() using "%d", "%o" and "%x" format specifier respectively.

 "%d" is used to input decimal value


 "%o" is used to input integer value in an octal format
 "%x" is used to input integer value in hexadecimal format

But, there is the best way to read the integer value in any format from decimal, octal and hexadecimal - there
is no need to use different format specifiers. We can use "%i"instead of using "%d", "%o" and "%x".

"%i" format specifier


It is used to read an integer value in decimal, octal or hexadecimal value.

 To input value in decimal format - just write the value in the decimal format, example: 255
 To input value in octal format - just write the value in octal format followed by "0", example: 03377
 To input value in hexadecimal format – just write the value in hexadecimal format followed
by "0x", example: 0xff

Program:

#include <stdio.h>

int main(void)
{
int num;

printf("Enter value: ");


scanf("%i", &num);
printf("num = %d\n", num);

return 0;
}

Output

Run1: Reading value in decimal format


Enter value: 255
num = 255

Run2: Reading value in octal format


Enter value: 0377
num = 255

Run3: Reading value in hexadecimal format


Enter value: 0xFF
num = 255

Input individual characters using scanf() in C


Here, we are going to learn how to input individual characters using single scanf() function in C programming
language?
Submitted by IncludeHelp, on September 12, 2018

To understand the functionally of scanf() while reading characters, we need to understand its flow, Consider the
following statement:

scanf ("%c%c%c", &x, &y, &z);

Now, if the input is "a b c", then 'a' will be assigned to variable x, SPACE will be assigned to variable y and 'b' will be
assigned to variable z.

Thus, scanf() reads the characters as well as space, tab and new line character.

So to read character values after skipping spaces, tabs we need to skip any value between two character values and
this is possible by using skip format specifier "%*c".

Program 1: without skipping spaces between characters

#include <stdio.h>

int main(void)
{
char x;
char y;
char z;

//input
printf("Enter 3 character values: ");
scanf ("%c%c%c", &x, &y, &z);

//print
printf("x= \'%c\' \n", x);
printf("y= \'%c\' \n", y);
printf("z= \'%c\' \n", z);

return 0;
}

Output

Enter 3 character values: a b c


x= 'a'
y= ' '
z= 'b'
Here, x contains 'a', y contains ' ' (space) and z contains 'b'.

Program 2: By skipping spaces or any character between characters

#include <stdio.h>

int main(void)
{
char x;
char y;
char z;

//input
printf("Enter 3 character values: ");
scanf ("%c%*c%c%*c%c", &x, &y, &z);

//print
printf("x= \'%c\' \n", x);
printf("y= \'%c\' \n", y);
printf("z= \'%c\' \n", z);

return 0;
}

Output

Enter 3 character values: a b c


x= 'a'
y= 'b'
z= 'c'

Input individual characters using scanf() in C


Here, we are going to learn how to input individual characters using single scanf() function in C programming
language?
Submitted by IncludeHelp, on September 12, 2018

To understand the functionally of scanf() while reading characters, we need to understand its flow, Consider the
following statement:

scanf ("%c%c%c", &x, &y, &z);

Now, if the input is "a b c", then 'a' will be assigned to variable x, SPACE will be assigned to variable y and 'b' will be
assigned to variable z.

Thus, scanf() reads the characters as well as space, tab and new line character.

So to read character values after skipping spaces, tabs we need to skip any value between two character values and
this is possible by using skip format specifier "%*c".

Program 1: without skipping spaces between characters


#include <stdio.h>

int main(void)
{
char x;
char y;
char z;

//input
printf("Enter 3 character values: ");
scanf ("%c%c%c", &x, &y, &z);

//print
printf("x= \'%c\' \n", x);
printf("y= \'%c\' \n", y);
printf("z= \'%c\' \n", z);

return 0;
}

Output

Enter 3 character values: a b c


x= 'a'
y= ' '
z= 'b'

Here, x contains 'a', y contains ' ' (space) and z contains 'b'.

Program 2: By skipping spaces or any character between characters

#include <stdio.h>

int main(void)
{
char x;
char y;
char z;

//input
printf("Enter 3 character values: ");
scanf ("%c%*c%c%*c%c", &x, &y, &z);

//print
printf("x= \'%c\' \n", x);
printf("y= \'%c\' \n", y);
printf("z= \'%c\' \n", z);

return 0;
}

Output

Enter 3 character values: a b c


x= 'a'
y= 'b'
z= 'c'

Skip characters while reading integers using scanf() in C


Here, we are going to learn how to skip any character between integers while input using scanf() function in C
programming language?
Submitted by IncludeHelp, on September 10, 2018

Let suppose, we want to read time in HH:MM:SS format and store in the variables hours, minutes and seconds, in
that case we need to skip columns (:) from the input values.

There are two ways to skip characters:

1. Skip any character using %*c in scanf


2. And, by specifying the characters to be skipped

1) Skip any character using %*c in scanf


%*c skips a character from the input. For example, We used %d%*c%d and the Input is 10:20 – : will be skipped, it will
also skip any character.

Example:

Input
Enter time in HH:MM:SS format 12:12:10

Output:
Time is: hours 12, minutes 12 and seconds 10

Program:

#include <stdio.h>

int main ()
{
int hh, mm, ss;

//input time
printf("Enter time in HH:MM:SS format: ");
scanf("%d%*c%d%*c%d", &hh, &mm, &ss) ;
//print
printf("Time is: hours %d, minutes %d and seconds %d\n" ,hh, mm, ss) ;

return 0;
}

Output

Enter time in HH:MM:SS format: 12:12:10


Time is: hours 12, minutes 12 and seconds 10

2) By specifying the characters to be skipped


We can specify the character that are going to be used in the input, for example input is 12:12:10 then the
character : can be specified within the scanf() like, %d:%d:%d.

Example:

Input
Enter time in HH:MM:SS format 12:12:10

Output:
Time is: hours 12, minutes 12 and seconds 10

Program:

#include <stdio.h>

int main ()
{
int hh, mm, ss;

//input time
printf("Enter time in HH:MM:SS format: ");
scanf("%d:%d:%d", &hh, &mm, &ss) ;
//print
printf("Time is: hours %d, minutes %d and seconds %d\n" ,hh, mm, ss) ;

return 0;
}

Output

Enter time in HH:MM:SS format: 12:12:10


Time is: hours 12, minutes 12 and seconds 10

Read a memory address using scanf() and print its value in C


Here, we are going to learn how to read a memory address using scanf() and print value stored at the given
memory address in C programming language?
Submitted by IncludeHelp, on September 12, 2018

Here, we have to input a valid memory address and print the value stored at memory address in C.

To input and print a memory address, we use "%p" format specifier – which can be understood as "pointer format
specifier".

Program:

In this program - first, we are declaring a variable named numand assigning any value in it. Since we cannot predict a
valid memory address. So here, we will print the memory address of num and then, we will read it from the user and
print its value.

#include <stdio.h>

int main(void)
{
int num = 123;
int *ptr; //to store memory address

printf("Memory address of num = %p\n", &num);

printf("Now, read/input the memory address: ");


scanf ("%p", &ptr);

printf("Memory address is: %p and its value is: %d\n", ptr, *ptr);

return 0;
}

Output

Memory address of num = 0x7ffc505d4a44


Now, read/input the memory address: 7ffc505d4a44
Memory address is: 0x7ffc505d4a44 and its value is: 123

Explanation:

In this program, we declared an unsigned int variable named num and assigned the variable with the value 123.

Then, we print the value of num by using "%p" format specifier – it will print the memory address of num – which
is 0x7ffc505d4a44.

Then, we prompt a message "Now, read/input the memory address: " to take input the memory address – we input
the same memory address which was the memory address of num. The input value is 7ffc505d4a44. And stored the
memory address to a pointer variable ptr. (you must know that only pointer variable can store the memory
addresses. Read more: pointers in C language).

Note: While input, "0x" is not required.

And finally, when we print the value using the pointer variable ptr. The value is 123.

Printing an address of a variable in C


Here, we are going to learn how to print the memory address of a variable in C programming language?
To print the memory address, we use '%p' format specifier in C.
Submitted by IncludeHelp, on September 13, 2018

To print the address of a variable, we use "%p" specifier in C programming language. There are two ways to get the
address of the variable:

1. By using "address of" (&) operator


2. By using pointer variable

1) By using "address of" (&) operator


When we want to get the address of any variable, we can use “address of operator” (&) operator, it returns the
address of the variable.
Program:

#include <stdio.h>

int main(void)
{
// declare variables
int a;
float b;
char c;

printf("Address of a: %p\n", &a);


printf("Address of b: %p\n", &b);
printf("Address of c: %p\n", &c);

return 0;
}

Output

Address of a: 0x7ffd3d518618
Address of b: 0x7ffd3d51861c
Address of c: 0x7ffd3d518617

2) By using pointer variable


A pointer is the type of a variable that contains the address of another variable, by using the pointer; we can also get
the address of another variable.

Read more: Pointers in C language

Program:

#include <stdio.h>

int main(void)
{
// declare variables
int a;
float b;
char c;

//Declare and Initialize pointers


int *ptr_a = &a;
float *ptr_b = &b;
char *ptr_c = &c;

//Printing address by using pointers


printf("Address of a: %p\n", ptr_a);
printf("Address of b: %p\n", ptr_b);
printf("Address of c: %p\n", ptr_c);

return 0;
}

Output
Address of a: 0x7ffd3d518618
Address of b: 0x7ffd3d51861c
Address of c: 0x7ffd3d518617

Note: At every run output may change.

Read a memory address using scanf() and print its value in C


Here, we are going to learn how to read a memory address using scanf() and print value stored at the given
memory address in C programming language?
Submitted by IncludeHelp, on September 12, 2018

Here, we have to input a valid memory address and print the value stored at memory address in C.

To input and print a memory address, we use "%p" format specifier – which can be understood as "pointer format
specifier".

Program:

In this program - first, we are declaring a variable named numand assigning any value in it. Since we cannot predict a
valid memory address. So here, we will print the memory address of num and then, we will read it from the user and
print its value.

#include <stdio.h>

int main(void)
{

int num = 123;


int *ptr; //to store memory address

printf("Memory address of num = %p\n", &num);

printf("Now, read/input the memory address: ");


scanf ("%p", &ptr);

printf("Memory address is: %p and its value is: %d\n", ptr, *ptr);

return 0;
}

Output

Memory address of num = 0x7ffc505d4a44


Now, read/input the memory address: 7ffc505d4a44
Memory address is: 0x7ffc505d4a44 and its value is: 123

Explanation:

In this program, we declared an unsigned int variable named num and assigned the variable with the value 123.

Then, we print the value of num by using "%p" format specifier – it will print the memory address of num – which
is 0x7ffc505d4a44.
Then, we prompt a message "Now, read/input the memory address: " to take input the memory address – we input
the same memory address which was the memory address of num. The input value is 7ffc505d4a44. And stored the
memory address to a pointer variable ptr. (you must know that only pointer variable can store the memory
addresses. Read more: pointers in C language).

Note: While input, "0x" is not required.

And finally, when we print the value using the pointer variable ptr. The value is 123.

Printing an address of a variable in C


Here, we are going to learn how to print the memory address of a variable in C programming language?
To print the memory address, we use '%p' format specifier in C.
Submitted by IncludeHelp, on September 13, 2018

To print the address of a variable, we use "%p" specifier in C programming language. There are two ways to get the
address of the variable:

1. By using "address of" (&) operator


2. By using pointer variable

1) By using "address of" (&) operator


When we want to get the address of any variable, we can use “address of operator” (&) operator, it returns the
address of the variable.

Program:

#include <stdio.h>

int main(void)
{
// declare variables
int a;
float b;
char c;

printf("Address of a: %p\n", &a);


printf("Address of b: %p\n", &b);
printf("Address of c: %p\n", &c);

return 0;
}

Output

Address of a: 0x7ffd3d518618
Address of b: 0x7ffd3d51861c
Address of c: 0x7ffd3d518617

2) By using pointer variable


A pointer is the type of a variable that contains the address of another variable, by using the pointer; we can also get
the address of another variable.

Read more: Pointers in C language

Program:

#include <stdio.h>

int main(void)
{
// declare variables
int a;
float b;
char c;

//Declare and Initialize pointers


int *ptr_a = &a;
float *ptr_b = &b;
char *ptr_c = &c;

//Printing address by using pointers


printf("Address of a: %p\n", ptr_a);
printf("Address of b: %p\n", ptr_b);
printf("Address of c: %p\n", ptr_c);

return 0;
}

Output

Address of a: 0x7ffd3d518618
Address of b: 0x7ffd3d51861c
Address of c: 0x7ffd3d518617

Note: At every run output may change.

printf() examples/variations in C
Here, we are going to learn about the printf(), its usages with different types of format specifiers in the C
programming language?
Submitted by IncludeHelp, on September 14, 2018

As we know that, printf() is used to print the text and value on the output device, here some of the examples that
we wrote to use the printf() in a better way or for an advance programming.

1) Print normal text

printf ("Hello world");

Output

Hello world
2) Print text in new line

printf ("Hello world\nHow are you?");

Output

Hello world
How are you?

3) Print double quote

To print double quote, we use \".

printf("Hello \"World\", How are you?\n");

Output

Hello "World", How are you?

4) Print percentage sign (%)

To print percentage sign/ character, we use %%.

printf ("Hey I got 84.20%% in my final exams\n");

Output

Hey I got 84.20% in my final exams

5) Print octal value

To print octal value, we use %o (It's alphabet o in lowercase)

int num = 255;


printf("num in octal format: %o\n", num);

Output

num in octal format: 377

6) Print hexadecimal value (with lowercase alphabets)

To print hexadecimal value, we use %x (its alphabet 'x' in lowercase) - as we know that a hexadecimal value contains
digits from 0 to 9 and alphabets A to F, "%x" prints the alphabets in lowercase.

int num = 255;


printf ("num in hexadecimal format(lowercase) : %x\n", num);
Output

num in hexadecimal format(lowercase) : ff

7) Print hexadecimal value (with uppercase alphabets)

To print hexadecimal value, we use %X (it's alphabet X in uppercase) - as we know that a hexadecimal value contains
digits from o to 9 and alphabets A to F, "%X" prints the alphabets in uppercase.

int num = 255;


printf ("num in hexadecimal format(uppercase) : %X\n", num);

Output

num in hexadecimal format(uppercase) : FF

8) Print long string using \ (slash)

If there is a long string, that you want to print with a single printf() with two or more lines, we can use slash (\).

printf ("Hello world, how are you?\


I love C programing language.\n");

Output

Hello world, how are you? I love C programing language.

9) Print backslash (\)

To print backslash (\), we use double backslash (\\).

printf ("The file is store at c:\\files\\word_files\n");

Output

The file is store at c:\files\word_files

10) To get total number of printed characters

We can also get the total number of printed character using printf(), printf() returns the total number of printed
character, that we can store in a variable and print.

int len = 0;
len = printf ("Hello\n");
printf ("Length: %d\n", len);

Output

Hello
Length: 6

11) Print integer value 5 digit left padded with 0

To print value with 0 padded in 5 digits, we can use "%05d".

int num = 255;


printf ("num (padded): %05d\n", num);

Output

num (padded): 00255

12) Print text with left and right padding

To print left padded text with space, we use "%20s" - Here, 20 is the number of characters, if string contains 5
characters then 15 spaces will be added at the left of the text.

Similarly, to print right padded text with space, we use a flag "-" like "%-20s" - Here, 20 is the number of characters,
if string contains 5 characters then 15 spaces will be added at the right of the text.

printf ("str1=\"%20s\", str2=\"%-20s\"\n", "Hello", "World");

Output

str1=" Hello", str2="World "

13) Print float value to specified number of digits after the decimal point

To print float value with specified number of digits after the decimal, we use "%.2f". Here, 2 is the number of digits
after the decimal point.

float val = 1.234567;


printf("val = %.2f\n", val);

Output

val = 1.23

14) Print integer value with "%i" format specifier

While printing the value "%d" and "%i" are same, they are used to print an integer value, we can also print the
integer value by using "%i".

int num = 255;


printf("num = %i \n", num);
Output

num = 255

15) “%p” can be used to print the address of a variable

Since, address of the variable is a large hexadecimal value - to print it we should not (or cannot) use "%d", "%i" etc.
To print an address of a variable, we must use "%p".

int num = 255;


printf("Address of num is: %p\n", &num);

Output

Address of num is: 0x7ffca0b5855c

Example with all above printf() statements


#include <stdio.h>

int main()
{
int num = 255;
int len = 0;
float val = 1.234567;

printf("Hello World");
printf("Hello world\nHow are you?");
printf("Hello \"World\", How are you?\n");
printf ("Hey I got 84.20%% in my final exams\n");
printf("num in octal format: %o\n", num);
printf ("num in hexadecimal format(lowercase) : %x\n", num);
printf ("num in hexadecimal format(uppercase) : %X\n", num);
printf ("Hello world, how are you?\
I love C programing language.\n");
printf ("The file is store at c:\\files\\word_files\n");
len = printf ("Hello\n");
printf ("Length: %d\n", len);
printf ("num (padded): %05d\n", num);
printf ("str1=\"%20s\", str2=\"%-20s\"\n", "Hello", "World");
printf("val = %.2f\n", val);
printf("num = %i \n", num);
printf("Address of num is: %p\n", &num);

return 0;
}

Output

Hello WorldHello world


How are you?Hello "World", How are you?
Hey I got 84.20% in my final exams
num in octal format: 377
num in hexadecimal format(lowercase) : ff
num in hexadecimal format(uppercase) : FF
Hello world, how are you? I love C programing language.
The file is store at c:\files\word_files
Hello
Length: 6
num (padded): 00255
str1=" Hello", str2="World "
val = 1.23
num = 255
Address of num is: 0x7ffca0b5855c

You might also like