For reading and writting a string the format specifier is %s and no & is needed
#include< stdio.h >
int main()
{
char str[30];
printf("Enter the string\n");
scanf("%s",str);
printf("String=%s",str);
return;
}
The scanf() function fills in the character typed at keyboard into the str[] array until the blank space or enter key is hit. If blank space or enter key is hit scanf() automatically place a '\0' in the array.
Normally the %s will read a string upto a blank space. To read a muti word string untill the end of line including blank space use %[^\n]s
#include< stdio.h >
int main()
{
char str[100];
printf("ENter the string\n");
scanf("%[^\n]s", str);
printf("String=%s",str);
return;
}
Output:
Enter the string
welcome honey
String=Welcome honey
Other way of reading multiword string is gets() and puts(). But it is dangerous to use gets() in programs so try to avoid gets()
#include< stdio.h >
int main()
{
char str[30];
printf("Enter the string\n");
gets(str);
puts(str);
return;
}
Pointer and String:
A string can be stored in 2 forms
char str[]="Welcome"; //here Welcome is stored in a location called str
char *str="Welcome"; //here Welcome is stored in some other location i memory and assign the address of the string in a char pointer
The advantage of pointing a string using a character pointer is we cannot assign a string to another string but we can assign a char pointer to another char pointer
char str[]="WELCOME";