In C, you can read and write strings using a variety of functions from the standard library. Here are some commonly used functions for reading and writing strings:
1. `printf`: This function is used to print a formatted string to the console. You can use the `%s` format specifier to print a string.
```c
char greeting[] = "Hello, world!";
printf("%s", greeting);
```
Output: `Hello, world!`
2. `scanf`: This function is used to read input from the console. You can use the `%s` format specifier to read a string.
```c
char name[100];
printf("Enter your name: ");
scanf("%s", name);
printf("Hello, %s!\n", name);
```
Output (if user enters "Alice"): `Hello, Alice!`
Note that `scanf` reads only a single word at a time. If you want to read a line of text including spaces, you can use the `fgets` function instead.
3. `fgets`: This function is used to read a line of text from a file or the console. You need to specify the maximum number of characters to read and the input stream.
```c
char buffer[100];
printf("Enter a sentence: ");
fgets(buffer, 100, stdin);
printf("You entered: %s", buffer);
```
Output (if user enters "The quick brown fox jumps over the lazy dog."): `You entered: The quick brown fox jumps over the lazy dog.`
Note that `fgets` reads the newline character `\n` as part of the input, so you may need to remove it if you want to compare or manipulate the string.
4. `puts`: This function is used to print a string to the console followed by a newline character.
```c
char message[] = "Hello, world!";
puts(message);
```
Output: `Hello, world!`
5. `gets`: This function is used to read a line of text from the console, but it is considered unsafe and is no longer recommended due to potential buffer overflow vulnerabilities. It is recommended to use `fgets` instead.
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc