printf and scanf

can someone teach me to use printf and scanf for accepting and displaying integers,characters,integer arrays,strings,etc in C++.

1 Like

for integers-:
int a;
scanf("%d",&a);
printf("%d",a);

for long in place of %d,use %ld
for long long int use %lld
and for unsigned use %llu

for characters-:
for single character like
char ch;
scanf("%c",&ch);
printf("%c",ch);

for array of chars-:
char ch[1001];
scanf("%s",ch);
printf("%s",ch);

if your input contains words with spaces then go for this-:
char ch[1001];
scanf(" %[^\n]s", ch);

for string-:
string s;
scanf("%s",&s);
printf("%s",s);

6 Likes

To take integer input

scanf("%<format-specifier1> %<format-specifier2>",&<variable-name1>,&<variable-name2>);

Example

int a;
scanf("%d",&a);

char c;
scanf("%c",&c);

To give integer output

printf("%<format-specifier1> %<format-specifier2>",<variable-name1>,<variable-name2>);

eg

printf("%d",a);

printf just dumps the characters in the first parameter as it is.

 char s[]="rahul";
 printf("Hello World %s",s);

will print Hello World rahul

Each primitive datatype has its unique format specifier.

Refer to this link for the whole list:Link

2 Likes
  • printf();

It is output statement,it displays information which are in double cotes

void main()

{

printf(ā€œhello worldā€);

}

  • scanf();

It is a input statement,which can assign value for a variable;

Ex:x=10;

x-variable 10-the value a assign to the value

scanf("%d",&x);

%d is integer datatype.(if ur using float values(0.746) it should be %f).

prgrm

void main()

{
int x;


scanf("%d",&x);

printf(ā€œthe value of x=%dā€,x);
}

1 Like

%d -> integers(int)

%lld -> long long int

%c -> character(char)

%s -> string (character array) // it breaks at next space(ā€™ ') or ā€˜\nā€™

For integer arrays :

Let a[100] is an array.

If you suppose need to take n integers in the array, where 0 < n <= 100. You can input in array like thisā€¦

int i = 0;
int a[100];
int n; //you can give a number here or at run time using scanf().
while(i<n)
{
    scanf("%d",&a[i]);
    i++;
}
1 Like

for array

printf("%d",a[i]);

same with scanf

scanf("%d",&a[i]);

where ā€˜iā€™ is index

for example,

int array[5];

for(int i=0;i<5;i++)

scanf("%d",&a[i]);

for(int i=0;i<5;i++)

printf("%d",a[i]);

Pleaseā€¦I really need some help

Thanks. :slight_smile:

What about integer arrays?

Thanks alot. I was so confused over it for the past hour.

1 Like