C scanf() function : C Reference

Scanf : Reading or Accepting String From User in C

In C Programming we can use scanf function from stdio.h header file to read string. Scanf function is commonly used for accepting string.

Syntax for Accepting String :

scanf("%s",Name_Of_String_Variable);

Live Example :

#include<stdio.h>
void main()
{
char name[20];
printf("\nEnter the Name : ");
scanf("%s",name);
}

Explanation : Scanf Program

In the above program we are accepting string from user using scnaf() function. We cannot use string ampersand address operator in the scanf() because string itself can be referred by address.

Some Rules and Facts :

  1. Format Specifier %s is used for Accepting String
  2. Scanf() function accepts only String before Space
#include<stdio.h>
int main()
{
char name[20];
printf("\nEnter the Name : ");
scanf("%s",name);
printf("Name of the Company : %s",name);
return(0);
}

Output :

Enter the Name : Google Incl
Name of the Company : Google

We can use scanf to Accept String With Spaces. Just Replace above scanf statement with this following statement -

scanf("%[\^n]", name );

Read more about Reading String with spaces using scanf.

Why We does not need Ampersand Operator :

  1. Scanf() needs a pointer to the variable that will store input.
  2. In the case of a string, you need a pointer to an array of characters in memory big enough to store whatever string is read in.
  3. When you declare something like char var[100], you make space for 100 chars with name[0] referring to the first char and name[99] referring to the 100th char.
  4. The array name by itself evaluates to exactly the same thing as &name[0], which is a pointer to the first character of the sequence, exactly what is needed by scanf.
  5. So all you need to do is -
  6. scanf("%s", name);
    

strcpy function : string.h >> Copy second string into First

strcpy function : string.h :Copy second string into First
What strcmp Actually Does ?

  1. Function takes two Strings as parameter
  2. Header File : String.h
  3. It returns string
  4. Perpose : Copies String2 into String1
  5. Original contents of String1 will be lost
  6. Original contents of String2 will remains as it is ….

Syntax :

char * strcpy ( char *string1, char *string2 ) ;

Return Type

Return TypeString
ParametersTwo Strings

Live Example 1

char s1[10] = "SAM" ;
char s2[10] = "MIKE" ;
strcpy (s1,s2);
puts (s1) ; // Prints : MIKE
puts (s2) ; // Prints : MIKE

strstr function : Finds first occurrence of sub-string in other string

Strstr function :  Finds first occurrence of sub-string in other string

Features :
  1. Finds the first occurrence of a sub string in another string
  2. Main Purpose : Finding Substring
  3. Header File : String.h
  4. Checks whether s2 is present in s1 or not
  5. On success, strstr returns a pointer to the element in s1 where s2 begins (points to s2 in s1).
  6. On error (if s2 does not occur in s1), strstr returns null.
Syntax :
     char *strstr(const char *s1, const char *s2);
Live Example 1 : Parameters as String initialized using Pointers

#include<stdio.h>
#include<string.h>

int main(void)
{
char *str1 = "c4learn.blogspot.com", *str2 = "spot", *ptr;
ptr = strstr(str1, str2);
printf("The substring is: %sn", ptr);
return 0;
}

Output  :

   The substring is: spot.com

Live Example 2: Passing Direct Strings

#include<stdio.h>
#include<string.h>

void main()
{
char *ptr;
ptr = strstr("c4learn.blogspot.com","spot");
printf("The substring is: %sn", ptr);
}

Output  :

   The substring is: spot.com

Bookmark & Share

sscanf function : stdio.h functions in C Programming

sscanf Function : Stdio.h
Syntax :

int sscanf (const char *buffer, const char *format [, address, ...]);

What it actually does ?

  1. Data is read from array Pointed to by buffer rather than stdin.
  2. Return Type is Integer
  3. Return value is nothing but number of fields that were actually assigned a value

Live Example:

char name[20];
int age,salary;
sscanf("Ram 23 4000 " ," %s %d %d ",name,&age,&salary);

Explanation of above Example :

  • We accept values from user and store them into Respective memory Locations
  • But by using sscanf functions instead of accepting data from stdin , we are reading data from the array
  • In the above Example “Ram 23 4000” are three values are assigned to name,age and salary

In short :

Variable NameValue
Name
Ram
age
23
salary
4000

sprintf function : sends formatted output to String

Sprintf function : sends formatted output to String


Features :

  1. Output is Written into String instead of Displaying it on the Output Devices .
  2. Return value is integer ( i.e Number of characters actually placed in array / length of string )
  3. String is terminated by ‘\0’
  4. Main Per pose : Sending Formatted output to String
  5. Header File : Stdio.h

Syntax :

int sprintf(char *buf,char format,arg_list);

Live Example :

int age = 23 ;
char str[100];
sprintf( str , "My age is %d",age);
puts(str);

Output of Above Program :

My age is 23 

Analysis of Source Code : - Just keep in mind that

  • Assume that we are using printf then we get output “My age is 23”
  • What does printf does ? —- Just Print the Result on the Screen
  • Similarly Sprintf stores result “My age is 23” into string str instead of printing it.

Sprintf Function in C

strcmp function : string.h >> Compare two strings

strcmp function >> string.h >> Compare two strings

What strcmp Actually Does ?

  1. Function takes two Strings as parameter
  2. It returns integer .

What strcmp Actually Does ?

  1. Function takes two Strings as parameter
  2. It returns integer .

Syntax :

int strcmp ( char *s1, char *s2 ) ;

Return Type

Return TypeCondition
-ve ValueString1 < String2
+ve ValueString1 > String2
0 ValueString1 = String2

Live Example 1 : Two strings are Equal

char s1[10] = "SAM",s2[10]="SAM" ;
int len;
len = strcmp (s1,s2);
if (len == 0)
   printf ("Two Strings are Equal");

Live Example 2 : String1 is Greater than String2

char s1[10] = "SAM",s2[10]="sam" ;
int len;
len = strcmp (s1,s2);
printf ("%d",len); //-ve value

Reason :

  1. ASCII value of “SAM” is smaller than “sam”
  2. ASCII value of ‘S’ is smaller than ‘s’

Live Example 3 : String1 is Smaller than String1

char s1[10] = "sam",s2[10]="SAM" ;
int len;
len = strcmp (s1,s2);
printf ("%d",len); //+ve value

Reason :

  1. ASCII value of “SAM” is greater than “sam”
  2. ASCII value of ‘S’ is greater than ‘s’

Note :

  1. This function is Case sensitive
  2. Header file : string.h

strcat function : Concat two Strings in C >> String Operations

strcat function >> Concat two Strings >>  String Operations

What strcat Actually does ?
  1. Function takes 2 Strings / Character Array as Parameter
  2. Appends second string at the end of First String.

Parameter Taken2 Character Arrays / Strings
Return Type Character Array / String

Syntax :

char* strlen ( char * s1, char * s2);


Ways of Using Strcat Function :
Way 1 : Taking String Variable as Parameter
           char str1[20] = “Don” , str2[20] = “Bosqo”;
           strcat(str1,str2);
           puts(str1);
Way 2 : Taking String Variable which is Already Initialized using Pointer
           char *str1 = “Ind”,*str2 = “ia”;
           strcat(str1,str2);                     // Result stored in str1
           puts(str1);                             // Result : India
Way 3 : Writing Function in printf Statement

           printf(“nString :  “, strcat(“Ind”,”ia”));              


strlen function : C Programming : Find length of string (String Operation)

strlen() : Finding Length of String

While manipulating string or character array in c programming. We need to compute the length of the string , C library provides different string handling functions. In order to compute length of the string strlen() function is used.

Syntax of the strlen() function :

int strlen(char * str);

Explanation and Summary :

PointExplanation
No of Parameters1
Parameter TakenCharacter Array Or String
Return TypeInteger
DescriptionCompute the Length of the String
Header filestring.h

Different Ways of Using strlen() :

There are different ways of using strlen function. We can pass different parameters to strlen() function.

Way 1 : Taking String Variable as Parameter

char str[20];
int length ;
printf("\nEnter the String : ");
gets(str);
length = strlen(str);
printf("\nLength of String : %d ", length);

Way 2 : Taking String Variable which is Already Initialized using Pointer

char *str = "priteshtaral";
int length ;
length = strlen(str);
printf("\nLength of String : %d ", length);

Way 3 : Taking Direct String

int length ;
length = strlen("pritesh");
printf("\nLength of String : %d",length);

Way 4 : Writing Function in printf Statement

char *str = "pritesh";
printf("\nLength of String : %d", strlen(str));