- How to declare a character array to hold a name
- How
scanf("%s")reads a single word — and why it stops at the first space - How
fgetsreads an entire line, including spaces - How to read a
doublewithscanf("%lf") - How to mix string and numeric input in the same program
- The pitfalls of mixing
scanfandfgetsin one program
Reading strings and numbers in C
Reading a number in C is straightforward — scanf("%d", &x) for an int, scanf("%lf", &y) for a double. Reading a string, though, is where beginners trip up. C has no built-in string type; strings are arrays of characters terminated by a null byte ('\0'). Reading one requires either scanf with %s, or the safer fgets.
scanf("%s", name) reads a sequence of non-whitespace characters. It stops at the first space, tab, or newline. So if the user types "John Smith," scanf("%s", name) reads only "John" — the "Smith" stays in the input buffer, waiting to confuse the next scanf call. For single-word names (or first names), this is fine. For full names, it's a problem.
fgets(name, sizeof(name), stdin) reads an entire line — up to and including the newline — until the buffer is full or the input ends. It stops at newlines, and the newline is included in the buffer (unlike scanf). This makes it ideal for names with spaces. The catch: you have to strip the trailing newline if you don't want it in your string. That's the trade-off.
For this program, we'll show both approaches. The scanf version is simpler (but breaks on multi-word names). The fgets version is more robust (but requires a bit more code to handle the newline). Understanding both is essential — most real programs use fgets for line-oriented input, and scanf for structured token input.
💡 In one line: scanf("%s") reads one word — fine for first names. fgets reads the whole line — needed for full names. For salary, scanf("%lf") works either way.
Designing the employee program
The design has three decisions that matter:
| Decision | Choice | Reason |
|---|---|---|
| Name storage | char name[50]; | 50 bytes is plenty for most names. Use fgets with sizeof(name) to avoid overflow. |
| Salary type | double | Salary can have cents (e.g., 75000.50). int would truncate. |
| Input method | scanf for salary, fgets for name | fgets handles full names; scanf handles the numeric salary cleanly. |
The 50-byte array for the name is generous — most names fit in well under 50 characters. If you're storing many names (e.g., an array of employees), this could become wasteful, but for a single employee, it's fine. If you want to be safer, use fgets(name, sizeof(name), stdin), which limits the read to the buffer size, preventing buffer overflow.
For the salary, double is the right choice. Salaries are frequently fractional (annual salary 75000.50, hourly rate 15.75, etc.). Using int would round down, losing cents. Even if you expect whole-dollar salaries today, using double avoids future surprises.
🎯 Key idea: scanf("%s") is dangerous — it reads an unbounded number of characters into your buffer, which overflows if the input is longer than the buffer. Always use scanf("%49s", name) (with a width) or fgets. The width prevents overflow; fgets is generally safer and easier to reason about.
Complete C Programs
Here is the simple version using scanf for both inputs — fine for single-word names:
Program: simple scanf version (first name only)
#include <stdio.h>
int main(void) {
char name[50];
double salary;
printf("Enter employee name (single word): ");
scanf("%49s", name); /* %49s: read up to 49 chars, leave room for '\0' */
printf("Enter employee salary: ");
scanf("%lf", &salary);
printf("\n--- Employee Details ---\n");
printf("Name: %s\n", name);
printf("Salary: $%.2lf\n", salary);
return 0;
}
The %49s specifier limits the read to 49 characters, leaving room for the null terminator. This is important — writing scanf("%s", name) without a width allows buffer overflow, a classic security vulnerability. Always specify the maximum width when using %s.
And here is the robust version using fgets, which handles full names with spaces:
Program: fgets version (full name)
#include <stdio.h>
#include <string.h>
int main(void) {
char name[50];
double salary;
printf("Enter employee name (full name, can include spaces): ");
fgets(name, sizeof(name), stdin);
/* fgets includes the trailing newline; strip it for cleaner output */
size_t len = strlen(name);
if (len > 0 && name[len - 1] == '\n')
name[len - 1] = '\0';
printf("Enter employee salary: ");
scanf("%lf", &salary);
printf("\n--- Employee Details ---\n");
printf("Name: %s\n", name);
printf("Salary: $%.2lf\n", salary);
return 0;
}
This version reads the entire line into name using fgets, then strips the trailing newline manually (because fgets includes it, and we don't want "Jane Doe\n" printed as the name — the "Name: Jane Doe\n" would have an extra newline, causing a blank line before "Salary"). The strlen from <string.h> finds the length; the check name[len - 1] == '\n' ensures we only strip if the newline is actually there (it might not be if the buffer filled up before the newline).
A common pitfall: mixing fgets and scanf in the same program. If you read the name with fgets and then read the salary with scanf, the fgets consumes the entire line including the newline, so there's nothing left over for the scanf. But if you read the salary first with scanf and then the name with fgets, the scanf leaves a trailing newline in the buffer, which fgets immediately reads as the name — giving you an empty name. The order matters, and it's a common source of confusion. Our program reads the name first, then the salary, which works correctly.
Program Output
For the scanf version with a single-word name:
Enter employee name (single word): Alice
Enter employee salary: 75000
--- Employee Details ---
Name: Alice
Salary: $75000.00
The name "Alice" is read in full (it's a single word), the salary 75000 is read as a double, and both are printed with clear labels. The salary is formatted with %.2lf and a dollar sign.
For the fgets version with a full name:
Enter employee name (full name, can include spaces): Jane Doe
Enter employee salary: 85000.50
--- Employee Details ---
Name: Jane Doe
Salary: $85000.50
The full name "Jane Doe" is read correctly, including the space. The salary 85000.50 is read as a double and printed with two decimal places. Everything works as expected.
Here's what happens if you try the full name with the scanf version:
Enter employee name (single word): Jane Doe
Enter employee salary:
--- Employee Details ---
Name: Jane
Salary: $0.00
The scanf("%49s", name) reads only "Jane" — the "Doe" stays in the input buffer. Then the next scanf("%lf", &salary) tries to read a double, but the first character it sees is 'D' (from "Doe"), which isn't a valid number. scanf fails, leaves salary uninitialized (or 0, depending on prior state), and returns 0. The program proceeds with the broken state, printing "Jane" and "$0.00" — silently wrong.
This is why fgets is preferable for names — it handles spaces correctly, avoiding this entire class of bug. The trade-off is the extra code to strip the newline, but that's a small price for correctness.
🔍 Try this: run the scanf version with a very long name (say, 60 characters). The %49s width limits the read to 49 characters, but if the input is exactly 50 or more, the rest stays in the buffer — and the next scanf fails for the same reason. Then try the same with fgets — it reads exactly up to sizeof(name) - 1 characters and null-terminates, so there's no overflow. fgets is the safer choice.
Step-by-Step Explanation
Let's walk through the fgets version — the more robust of the two.
1. The includes
#include <stdio.h> — for printf, scanf, and fgets.
#include <string.h> — for strlen. This header declares the string manipulation functions (length, copy, compare, etc.).
2. The declarations
char name[50]; — declares a character array of 50 bytes. The array can hold up to 49 characters plus the null terminator ('\0'). If a name is longer than 49 characters, it will be truncated (either by fgets reading only 49 chars, or by overflow if using the unsafe scanf("%s")).
double salary; — declares a double for the salary. A double occupies 8 bytes and can hold values from about 1.8 × 10−308 to 1.8 × 10308, with about 15 significant decimal digits of precision. For any reasonable salary (up to billions of dollars), this is plenty.
3. Reading the name with fgets
fgets(name, sizeof(name), stdin); — reads up to sizeof(name) - 1 bytes (49 in this case) from stdin into name, stopping at a newline or EOF. It always null-terminates (appends a '\0' after the last byte read), so name is a valid C string afterward. If the user typed "Jane Doe\n", the function stores "Jane Doe\n" (10 characters plus null) into name.
Unlike scanf("%s"), fgets doesn't strip the newline. If you print "Name: %s\n" with the newline still in name, you get "Name: Jane Doe\n\n" — two newlines, resulting in a blank line. To avoid this, we need to strip the newline.
4. Stripping the trailing newline
size_t len = strlen(name); — computes the current length of the string (excluding the null terminator). For "Jane Doe\n", len is 9.
if (len > 0 && name[len - 1] == '\n') name[len - 1] = '\0'; — if the last character (at index len - 1) is a newline, replace it with a null byte. This effectively truncates the string by one character, removing the newline. After this, name contains "Jane Doe" (8 chars plus null).
The len > 0 check is important — if the string is empty, len - 1 would underflow (well, it would be a huge number, causing undefined behavior when we index name[len - 1]). The check prevents that.
A subtlety: if the user's name was longer than 49 characters, fgets would have read exactly 49 characters, and there would be no newline at the end (the newline stayed in the input buffer). In that case, the check name[len - 1] == '\n' would be false, and we wouldn't strip anything — which is correct, because there's nothing to strip.
5. Reading the salary
scanf("%lf", &salary); — reads a double from the input into salary. The %lf specifier matches double. If the user typed "85000.50\n", scanf reads 85000.50 and leaves the newline in the input buffer (which is fine — it's the last input).
There's no fgets vs scanf mixing issue here, because fgets already consumed its entire line (including the newline). The subsequent scanf starts fresh on the next line, so it reads the salary cleanly. If we'd reversed the order — scanf for salary, then fgets for name — the fgets would have found the leftover newline from scanf and read an empty string. Order matters.
6. Printing the details
printf("\n--- Employee Details ---\n"); — prints a separator with a blank line before and after, making the output easier to scan. The \n at the start puts a blank line between the prompt and the details; the \n at the end puts the next output on a new line.
printf("Name: %s\n", name); — prints the name with a label. The three spaces after "Name:" align the colons (with "Salary:"), making the output visually cleaner. The %s specifier prints a C string (null-terminated char array) up to but not including the null terminator.
printf("Salary: $%.2lf\n", salary); — prints the salary with a dollar sign and two decimal places. The %.2lf ensures exactly two decimal places (e.g., "$75000.50"). Without the .2, it would print six decimal places — too much for a currency amount.
7. Why the scanf version fails on multi-word names
When you call scanf("%49s", name) and the user types "Jane Doe", scanf reads "Jane" (stopping at the space) and leaves " Doe\n" in the input buffer. The subsequent scanf("%lf", &salary) tries to read a double, but the first non-whitespace character it finds is 'D' — not a digit, sign, or decimal point. scanf fails to match, returns 0, and leaves salary unchanged (or 0 if never initialized).
This is a classic bug that trips up beginners. The fix is to use fgets for the name (which reads the whole line) or to use a format that explicitly consumes the rest of the line, like scanf("%49[^\n]", name). The fgets approach is cleaner and safer.
8. The scanf("%49[^\n]", name) alternative
For completeness, here's another way to read a full line with scanf:
scanf(" %49[^\n]", name);
The %49[^\n] specifier reads up to 49 characters that are not newlines. The leading space before the % tells scanf to skip any leading whitespace (including the newline from a previous scanf). This reads the full line including spaces, up to 49 characters. It's a valid alternative to fgets, though less commonly used. The fgets version is generally recommended because it's easier to reason about the buffer size and the newline handling.
9. Security considerations
Buffer overflow is a real security issue. If you write scanf("%s", name) where name is a 50-byte array, and the user types a 100-character name, scanf writes past the end of the buffer, corrupting adjacent memory. This can crash the program or, in the wrong hands, become an exploit. Always specify the maximum width in %s (%49s for a 50-byte buffer) or use fgets, which respects the buffer size.
In real code, buffer overflow is one of the most serious vulnerabilities. Many exploits are based on deliberately overflowing a buffer to overwrite a return address or function pointer. Using fgets or width-limited scanf closes this attack vector.
10. Extending the program
This program reads one employee's details. To read many employees, wrap the code in a loop and store the data in arrays or structs. For example:
struct Employee {
char name[50];
double salary;
};
struct Employee employees[100];
int count = 0;
/* Read in a loop */
for (int i = 0; i < 100; i++) {
printf("Enter name (or 'quit' to stop): ");
fgets(employees[i].name, 50, stdin);
/* strip newline, check for "quit", read salary, etc. */
count++;
}
This is the natural next step — the program already reads one employee; generalizing to many requires structs (a topic covered later in the C tutorial series). The pattern is the same: read, store, repeat.
🎯 Key idea: always limit the input size when reading strings. scanf("%s") without a width is a buffer overflow waiting to happen — it's a security vulnerability, not just a bug. Use %49s (matching the buffer size minus 1) or fgets. The extra character of safety is worth the trouble.
Frequently Asked Questions
1. Why does scanf("%s") stop at the first space?
Because %s is defined to read a sequence of non-whitespace characters. Whitespace (spaces, tabs, newlines) terminates the input. This is useful for reading individual tokens (like a single word or a number), but not for reading full lines. Use fgets or %[^\n] for lines.
2. Why does fgets include the newline, while scanf doesn't?
It's a design choice — fgets is line-oriented, so it includes the newline to preserve the line structure. scanf is token-oriented, so it treats the newline as a separator and doesn't include it. Both are correct for their intended use. The downside of fgets is you need to strip the newline manually; the downside of scanf is you can't read multi-word input easily.
3. What happens if I mix scanf and fgets in the same program?
You get surprises. scanf leaves the trailing newline in the buffer. Then fgets reads that leftover newline as an "empty line" and returns immediately, giving you an empty string. This is a common bug. The fix is to consume the newline after scanf — for example, by calling getchar() once, or by adding a space at the start of the next scanf format. In our program, we read the name first (via fgets), then the salary (via scanf) — that order avoids the problem because fgets consumes the entire line first.
4. What's the difference between char name[50] and char *name?
char name[50] declares an array of 50 characters — the storage is reserved on the stack, and the array name name decays to a pointer to the first char when passed to functions. char *name declares a pointer — it points to some character, but doesn't own any storage. You'd have to malloc storage or point it to an existing string. For a name field that will be filled with user input, char name[50] is the correct choice — it provides the storage. char *name would crash if you tried to fgets into it without allocation.
5. Why do we use double for salary instead of float or int?
int can't hold cents — 75000.50 would be truncated to 75000. float can hold cents, but only 7 significant digits, so 75000.50 becomes 75000.5 (losing precision) — and for very large salaries (millions of dollars), float loses even more precision. double has 15 significant digits, enough for any realistic salary. In financial applications, sometimes long long (in cents) is used instead of floating-point, to avoid rounding errors — but for general use, double is the standard choice.
6. What does %49s actually mean?
The %s is the format specifier for a string. The 49 is a field width — it tells scanf to read at most 49 characters. Since a C string needs a null terminator (1 byte), a 50-byte buffer can hold up to 49 characters plus the null. Writing %49s ensures scanf doesn't overflow the buffer. Without a width (%s alone), scanf reads until whitespace, which could be arbitrarily long — a buffer overflow waiting to happen.
💡 Tip: once this works, extend the program to read details for multiple employees. Use an array of struct Employee to hold each employee's name and salary, read them in a loop until the user enters "quit" for the name, and print a summary. You'll practice loops, arrays, structs, and string comparison (strcmp) — four essential C concepts — in one coherent program.