Reading and writing text

Text, stored as strings (arrays of characters), are a topic we will explore more fully later. However, it is important to get some basic input and output of strings sorted out because they are so useful for interacting with humans.

The conversion specifier for strings with scanf and printf is s. The type you want for a variable that can hold strings is char *. There is a little memory allocation going on here, with the m modifier with scanf and the free at the end (plus the necessary header, stdlib.h), but the following sample program should give you what you need to work with for reading a word from the standard input.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char *word;

    /* Read a word, allocating memory as necessary. */
    printf("Type one word, no spaces: ");
    scanf("%ms", &word);

    /* Say it back. */
    printf("You said, \"%s\".\n", word);

    /* Release the allocated memory. */
    free(word);
}

Many kinds of interesting inputs are just one word, but just as many inherently may have spaces in them, such as if you want to ask someone their name. This example introduces some other new types and techniques, but it reads a whole line of input and you can use it as starter code you can modify to set up your own program’s input.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    /* Will hold the string itself, NULL for now because empty. */
    char *line = NULL;

    size_t size;    /* The allocated size of the string, once it's read. */
    ssize_t length; /* The number of characters in the string. */

    /* Read a line, allocating memory as necessary. */
    printf("Type a whole line, spaces allowed: ");
    length = getline(&line, &size, stdin);

    /* Trim off a newline from the end. */
    if (line[length - 1] == '\n')
        line[length-- - 1] = '\0';

    /* Say it back. This is the same whether the string has
       spaces or not. */
    printf("You said, \"%s\".\n", line);

    /* Release the allocated memory. */
    free(line);
}
You have attempted of activities on this page