C String Input and Output
There are many ways to read a string from the user. Each has some different behaviour.
scanf with %s
It reads only one word. It stops at the first space.
#include <stdio.h>
int main(void) {
char name[30];
scanf("%29s", name);
printf("Hello, %s\n", name);
return 0;
}
Output:
Output of the above program is
Robin Sharma
Hello, Robin
No & is needed with %s, because the array name is already an address. The number 29 limits the input, so it cannot overflow the 30 bytes array.
fgets: read a full line
fgets() reads a line with spaces. It is the safe way.
#include <stdio.h>
#include <string.h>
int main(void) {
char name[30];
fgets(name, sizeof(name), stdin);
name[strcspn(name, "\n")] = '\0'; // remove the new line
printf("Hello, %s\n", name);
return 0;
}
Output:
Output of the above program is
Robin Sharma
Hello, Robin Sharma
fgets() also keeps the new line character (Enter key) in the string. The line with strcspn() removes it.
puts and printf
#include <stdio.h>
int main(void) {
char msg[] = "Learning C";
puts(msg); // prints and adds a new line
printf("%s\n", msg);
return 0;
}
Output:
Output of the above program is
Learning C
Learning C
Do not use gets()
gets() cannot check the size of the array, so it can write outside the memory. It was removed from the C11 standard. Use fgets().
Note:
If you use scanf("%d") and then fgets(), the left over new line from scanf can make fgets return an empty line. Read the number with fgets() too, or clear the input first.
Next: C String Functions.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |