Reading and Writing Strings

Reading and Writing Strings

Published by: Nuru

Published date: 21 Jun 2021

Reading and Writing Strings Photo

Reading and Writing Strings

Reading and Writing Strings are one of the operations performed on the character strings. These are the input/ output characters.
We use an input function scanf with %s format specification to read in a string of characters.

For Example:

Char name [20];
Scanf (“%s”, name);

  • There is no requirement of ‘&’ before the variable name or it is optional.

#include
int main ()
{
char str [100];
Printf ("Enter a string :");
Scanf ("%s", &str);
printf ("String = %s", str);
return 0;
}
For Output:
Enter String: Online
String: Online

  • Due to using of scanf (), it terminates the input of the first which space in the text.

For Instance:

#include
int main ()
{
char str [100];
printf ("Enter String: ");
scanf ("%s", str);
printf ("String = %s", str);
return 0;
}
If the input is Online Notes, then it will only read Online.
i.e.,

Output:
Enter String: Online Notes
String: Online

  • There should be maximum space to read the string. If not, the program will be terminated.

For Example:

#include
int main ()
{
char str [5];
printf ("Enter String: ");
scanf ("%s", str);
printf ("String = %s", str);
return 0;
}

Output:
Enter String: Online
Aborted (core dumped)

The size should be large to store all data. Otherwise, it will destroy anything that follows the array in the memory. And, we must not exceed the length of the data.

We can use an alternative method for reading the data in a string variable. That is, to use scanf () with the %c which has a count related to it. The %c conversion does not generate the NULL termination automatically like %s and % [ ].

#include
int main ()
{
char str [100];
printf ("Enter a string in lower case: ");
scanf ("% [a-z]", str);
printf ("String = %s\n", str);
return 0;
}

Output:
Enter a string in lower case: onlinenotes
string: onlinenotes

Enter a string in lower case: onlineNotes
string: online