32A. Reading and Writing Characters and Strings


Writing characters and strings

Use the following formats with printf.

%c

Write a single character. For example, if variable c has type char and value 'Z', then
  printf("%c", c);
writes Z.

If you write an integer with format %c, you get the character with that code. For example, the code for 'a' is 97, and

  printf("%c", 97);
writes a.


%s

Write a null-terminated string (without the null character). For example, if s is a variable of type char* and s points to string "camel", then
  printf("My pet %s is named Flower\n", s);
writes
My pet camel is named Flower


Reading characters and strings

Use the following formats with scanf.

%c

Read a single character. For example,
  char ch;
  scanf("%c", &ch);
reads one character and stores that character into ch. If you want to read the next non-white-space character, put a space in front of %c.
  char ch;
  scanf(" %c", &ch);

%s

Read a string. Statement
  char s[100];
  scanf("%s", s);
skips over white space (if any), then reads characters up to a white space character or the end of the input, storing the characters into array s. It adds a null character to the end.

Warning. Do not write

  char* s = new char[100];
  scanf("%s", &s);
Format %s wants the address of an array, not the address of a variable that points to an array.

Warning. The %s format does not allocate memory. Statements

  char* s;
  scanf("%s", s);
fail to initialize s. That makes scanf store characters at a memory address that is a dangling pointer.

Warning. Reading strings using %s is dangerous. If the string in the input is too long, scanf will store characters outside of the array. See %ms.


%ms

Read a string. Statement
  char* s;
  scanf("%ms", &s);
is similar to the same thing with %s, but %ms allocates enough memory to hold the string that it reads, and stores a pointer to the newly allocated array into s. Notice that, in this case, you do want &s. The parameter corresponding to %ms must have type char**.

The memory is allocated using malloc. To delete the array, use

  free(s);


%m[A-za-z]

This is similar to %ms, but it omits skipping over initial white space and reads a string consisting of zero or more letters. You can list individual characters, as in [aeiou], and can give character ranges, such as a-z. For example,
  char* p;
  scanf("%m[a-z], &p);
reads a string of lower-case letters.

%m[^A-za-z]

The ^ character means anything except these. So you get a string of nonletters.