What is C String Input and Output – Best Embedded C Programming Course

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

Free C Programming Course | Strings | Lecture 28

C String Input and Output

Read and print text safely with printf, scanf, fgets and puts, and learn why gets is gone.

Programs talk to people and to peripherals through text, so string input and output in C is a skill every beginner needs. In this free C tutorial we use the functions you will meet in real embedded C programming: printf, scanf, fgets and puts. We also see how one very old function, gets, turned into the textbook example of what not to do. Every program below was compiled and run, and the output is shown exactly as produced.

What You Will Learn

  • Printing strings with printf, puts and fputs
  • Controlling width, alignment and truncation with format specifiers
  • Reading a word with scanf and why a field width is mandatory
  • Reading a full line with fgets and stripping the newline
  • Why gets was removed from the language
  • Choosing the right function for each job

Prerequisites

The previous lecture on strings and the null terminator, plus basic printf and scanf usage from the Input-Output chapter.

String Input and Output in C: Printing Text

The conversion %s in printf takes a pointer to the first character and prints characters until it meets the null terminator. You can shape the output with a width and a precision. The program below prints the same board name in six ways.

#include <stdio.h>

int main(void)
{
    const char *board = "STM32F4";

    printf("[%s]\n",      board);     /* as is                  */
    printf("[%12s]\n",    board);     /* right aligned, width 12 */
    printf("[%-12s]\n",   board);     /* left aligned            */
    printf("[%.5s]\n",    board);     /* at most 5 characters    */
    printf("[%12.5s]\n",  board);     /* both together           */
    printf("[%*s]\n", 10, board);     /* width taken from args   */

    puts(board);                      /* text + newline          */
    fputs(board, stdout);             /* text, no newline        */
    putchar('\n');
    return 0;
}
gcc -std=c11 -Wall -Wextra -o ep_str_format ep_str_format.c
$ ./ep_str_format
[STM32F4]
[     STM32F4]
[STM32F4     ]
[STM32]
[       STM32]
[   STM32F4]
STM32F4
STM32F4
FormatMeaningResult for STM32F4
%sPrint the whole string[STM32F4]
%12sRight align in 12 columns[ STM32F4]
%-12sLeft align in 12 columns[STM32F4 ]
%.5sPrint at most 5 characters[STM32]
%12.5sWidth 12 and at most 5 characters[ STM32]
%*sWidth supplied as an argument[ STM32F4]

The precision (the number after the dot) is a quiet safety tool. When you print a buffer that might lack a terminator, such as a fixed-size field from a protocol packet, %.8s guarantees that printf never reads more than eight bytes.

puts, fputs and putchar

puts(s) writes the string and then adds a newline. fputs(s, stdout) writes the string and nothing else. putchar('\n') writes one character. The last two lines of the program output show that puts and fputs followed by putchar give the same result.

Tip for small devices

On a microcontroller, puts and fputs are lighter than printf, which pulls a large formatting engine into flash. If you only print fixed text, prefer them.

String Input and Output in C with scanf

Where the bytes go when scanf reads a word
KeyboardHyderabadspaceTelangananewline
scanf %15sHyderabadstops at space
Left in bufferspaceTelangananewline

scanf("%15s", word) skips any white space, copies characters up to the next white space, and writes the terminator. The number 15 is the field width. For char word[16] the width must be one less than the array size, because the terminator needs the last byte. Without a width, %s writes as many characters as the user types, which is a buffer overflow waiting to happen.

The next program reads a city with scanf and then an address line with fgets. Between them a small loop throws away the rest of the first line, otherwise the fgets would simply pick up the leftover text and the newline.

#include <stdio.h>
#include <string.h>

int main(void)
{
    char word[16];
    char line[32];

    printf("Type a city name: ");
    fflush(stdout);

    /* %15s stores at most 15 characters + the terminating zero. */
    if (scanf("%15s", word) != 1) {
        puts("nothing read");
        return 1;
    }
    printf("scanf kept   : [%s]\n", word);

    /* Throw away whatever is left on this input line. */
    int ch;
    while ((ch = getchar()) != '\n' && ch != EOF)
        ;

    printf("Type a full address: ");
    fflush(stdout);
    if (fgets(line, sizeof line, stdin) == NULL) {
        puts("nothing read");
        return 1;
    }

    /* fgets keeps the newline; strip it if present. */
    line[strcspn(line, "\n")] = '\0';
    printf("fgets kept   : [%s]\n", line);
    printf("length       : %zu\n", strlen(line));

    puts("done");   /* puts adds its own newline */
    return 0;
}
gcc -std=c11 -Wall -Wextra -o ep_str_read ep_str_read.c

We feed input through a pipe so you can reproduce the exact run. First, a normal case with two words in the first line:

$ printf 'Hyderabad Telangana\n12 Tank Bund Road\n' | ./ep_str_read
Type a city name: scanf kept   : [Hyderabad]
Type a full address: fgets kept   : [12 Tank Bund Road]
length       : 17
done

The word Telangana never reached the buffer. scanf stopped at the space, and the flush loop discarded the remainder. The address line was read completely, and its length is 17 characters, the same as strlen reports once the newline is removed.

Now an input that is longer than the buffer:

$ printf 'Visakhapatnam-Andhra-Pradesh\nNH16\n' | ./ep_str_read
Type a city name: scanf kept   : [Visakhapatnam-A]
Type a full address: fgets kept   : [NH16]
length       : 4
done

The width limit worked: only fifteen characters, Visakhapatnam-A, were stored, and the rest of the line was discarded. No memory was overwritten.

String Input and Output in C with fgets

fgets(buf, size, stream) reads at most size - 1 characters, stops after a newline, and always writes a terminator. It returns NULL at end of input or on error, so always check the return value. Unlike scanf, it keeps spaces. It also keeps the newline if the line fitted, which is why the program removes it:

line[strcspn(line, "\n")] = '\0';

strcspn returns the position of the first newline, or the length of the string if there is none. Writing a zero there removes the newline when present and does nothing harmful when absent. That makes it safer than the common line[strlen(line) - 1] = 0, which damages the last real character when the line was too long to contain a newline, and crashes on an empty string.

FunctionStops atKeeps spaces?Keeps newline?Bounded?
scanf("%s")White spaceNoNo (stays in input)Only with a width
scanf("%15s")White space or 15 charactersNoNo (stays in input)Yes
fgetsNewline or size-1 charactersYesYes, if it fitsAlways
getsNewlineYesNoNever. Removed

Why gets Was Removed

Older textbooks, including the book this course replaces, read lines with gets(str). The problem is that gets receives only a pointer. It cannot know whether your array holds 10 bytes or 10,000, so a long input writes straight over neighbouring variables and return addresses. The function was deprecated after C99 and removed from the standard in C11. Modern toolchains refuse or warn loudly:

$ gcc -std=c11 -Wall -o ep_old_gets ep_old_gets.c
ep_old_gets.c:6:5: warning: implicit declaration of function 'gets'; did you mean 'fgets'? [-Wimplicit-function-declaration]
/usr/bin/ld: ... in function `main':
ep_old_gets.c:(.text+0x28): warning: the `gets' function is dangerous and should not be used.

The replacement is fgets, exactly as shown above. If you maintain an old code base that still calls gets, change it before you do anything else.

Security note. Unbounded string input is one of the oldest firmware and server vulnerabilities. If an attacker controls the text, an overflowing copy can overwrite a return address and run code of their choosing. Always give every input function the size of the destination.

Choosing the Right Function

TaskBest choiceReason
Read one word or tokenscanf("%Ns")Skips white space, bounded
Read a line with spacesfgetsSafe and simple
Print fixed text with newlineputsLight and clear
Print fixed text, no newlinefputsNo formatting overhead
Print values mixed with textprintfFormat specifiers
Build text in memorysnprintfBounded, returns needed length

Common Mistakes in String Input and Output in C

  • Using %s without a width. Always limit the field.
  • Forgetting the leftover newline. A scanf followed by fgets often makes fgets return an empty line. Flush the line first.
  • Ignoring return values. Check scanf against the number of items you asked for, and fgets against NULL.
  • Passing the address-of operator to scanf with a char array. The array name already is an address, so write scanf("%15s", word), not &word.
  • Mixing up width and size. The width in %15s is one less than the array size 16.

Best Practices and Performance

  • Define the buffer size once, for example #define LINE_MAX_LEN 64, and use it for both the array and the call.
  • Prefer sizeof buf over a repeated number when the array is in scope.
  • Do not call printf in interrupt handlers. Queue the data and print it from the main loop.
  • On embedded targets, check whether your C library offers a reduced printf. Float formatting is the usual size hog.

Summary and Key Takeaways

  • String input and output in C is safe only when every function knows the size of its buffer.
  • printf("%s") prints until the terminator. Width and precision shape the result.
  • puts adds a newline, fputs does not.
  • scanf("%Ns") reads one word and needs a width of array size minus one.
  • fgets reads a line safely and keeps the newline, which you strip with strcspn.
  • gets is removed from C11. Never use it.

Conclusion

You can now handle string input and output in C with confidence and with bounds. The rule that ties everything together is simple: every function that writes into an array must be told how big the array is. In the next lecture of this free embedded C course we apply arrays to a practical problem, converting a decimal number to binary, octal and hexadecimal text.

Frequently Asked Questions

Why does scanf(“%s”) read only one word?

The %s conversion skips leading white space and then stops at the next white space character, such as a space, tab or newline. Typing New Delhi stores only New, and Delhi stays waiting in the input buffer.

How do I stop scanf from overflowing my array?

Put a field width one smaller than the array size, for example scanf(“%15s”, word) for char word[16]. The width counts characters and the terminator is added on top.

Which function is safest for string input and output in C when I need a whole line?

Use fgets(buf, sizeof buf, stdin). It never writes more than the size you give, and it keeps the newline if it fits, so strip the newline afterwards.

Why was gets removed from C?

gets has no way to know the size of the destination, so any long input overflows the buffer. It was deprecated after C99 and removed in C11. Use fgets instead.

What is the difference between puts and printf?

puts writes a string and then a newline. printf writes exactly what the format string describes and supports conversions. fputs writes a string with no newline.

How do I remove the newline that fgets keeps?

Use buf[strcspn(buf, “\n”)] = ‘\0’. It finds the first newline, or the terminator if there is none, and puts a zero there.

Is this part of the free C programming course?

Yes. It continues the strings topic in the free embedded C course on EmbeddedPathashala.

Keep Going With Free Embedded C

Next up: a number base converter built with arrays. Every lecture in this free C programming course is free and beginner friendly.

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →