Programming in C++

C-Strings

Gerald Senarclens de Grancy

Terminology

  • String
  • Standard input, standard output and standard error
  • Operator
    • A symbol representing an operation (eg.: mathematical operation)
    • There are arithmetic, logical, assignment, ... operators
  • Operator precedence
    • When in doubt, use parenthesis
    • In order to make your code more readable, use parenthesis
  • while loops

What is a C-String?

  • Sequence of characters
    • Details depend on the programming language
  • A C-string is a character array (char[])
  • C-strings are terminated with the value 0
    (0 corresponds to the ASCII character '\0',
    48 corresponds to the ASCII character '0')
char text[] = "Freedom";
Index 0 1 2 3 4 5 6 7
Character 'F' 'r' 'e' 'e' 'd' 'o' 'm' '\0'
Decimal Value 70 114 101 101 100 111 109 0
Address 0x7fffc8c013e4 0x7fffc8c013e5 0x...e6 0x...e7 0x...e8 0x...e9 0x...ea 0x...eb

Visualize execution

Purpose of Working with Text

Which problems do C-strings solve?

  • Input/output (I/O) required for basic communication with users
  • User interaction requires text
  • Prerequisite for reading and writing textual files
  • ...

Which problems do C strings cause?

  • C strings are "dumb" (not even aware of their length)
  • Limited to extended ASCII
  • Hard to use compared to string types in higher level languages
  • Security implications of C string functions

Reading User Input

Example: Read a Single Number via a C-String

#include <cstdio>

int main() {
  char line[5];  // max. 4 characters + 0 (same as '\0')
  int number = 0;
  printf("enter an integer (0 <= number <= 9999): ");
  fgets(line, sizeof(line), stdin);
  printf("You entered the text `%s`.\n", line);
  sscanf(line, "%d", &number);
  printf("This text, represented as an integer is `%d`.\n", number);
  return 0;
}

Download read_number.cpp

Example: Read a Single Number with C++

If you can, use proper C++ instead instead of C strings

#include <iostream>

int main() {
  int number = 0;
  std::cout << "enter an integer (0 <= number <= 9999): ";
  std::cin >> number;
  std::cout << "You entered " << number << std::endl;
  return 0;
}

Download cpp_read_number.cpp

Example: Read a C-String

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

int main() {
  char line[15];  // max. 14 characters + \0
  printf("enter your first name: ");
  fgets(line, 15, stdin);
  printf("{begin}%s{end}\n", line);
  line[strcspn(line, "\n")] = 0;  // remove final newline; '\0' == 0
  printf("{begin}%s{end}\n", line);
  return 0;
}

Download read_string.cpp

Example: Read a Single Number with C++

If you don't have to use C strings, use proper C++ instead

#include <iostream>
#include <string>

int main() {
  std::string line;
  std::cout << "enter your first name: ";
  std::cin >> line;
  std::cout << "{begin}" << line << "{end}" << std::endl;
  return 0;
}

Download cpp_read_string.cpp

Example: Convert C++ Strings to C Strings

Use C++ strings while possible, pass them as C strings when needed

#include <cstring>  // provides C string functions like `strcpy(.)`
#include <iostream>
#include <string>


int main() {
  std::string s("C++ strings are character arrays in the background");
  char c_string[100];  // standard C++ does not allow `s.length() + 1` here
  strcpy(c_string, s.c_str());  // `c_str()` returns a `const char*`
  std::cout << "C string: " << c_string << std::endl;
  return 0;
}

Visualize execution

C String Functions

String functions are included via <cstring>

Using string functions may lead to security issues.

stpcpy, strcasecmp, strcat, strchr, strcmp, strcoll, strcpy, strcspn, strdup, strfry, strlen, strncat, strncmp, strncpy, strncasecmp, strpbrk, strrchr, strsep, strspn, strstr, strtok, strxfrm, index, rindex

To get help, consult your manual :)

man 3 string

toupper(int c) and tolower(int c) are included via <cctype>

Example: Copy a String

#include <cstdio>
#include <cstring>

int main() {
  char name[] = "Pat";
  char destination[10];  // programmer is responsible for destination's size
  strcpy(destination, name);
  printf("Destination is `%s`\n", destination);
  return 0;
}

Visualize execution

Iterating Over a C-String

It is possible to iterate over a string using a while loop. The syntax is

while (condition) {
  // statements that repeat as long as `condition` evaluates to true
}

Loops can be interrupted with break.
The current iteration can be ended using continue.

while (condition) {
  // block of statements
  if (skip_remaining_iteration) {
    continue;  // skip rest of this iteration
  }
  if (loop_should_end_now) {
    break;  // leave the loop
  }
}

Example: Convert C String to Upper Case

#include <cctype>
#include <cstdio>

int main() {
  char input_text[] = "The world is beautiful!";
  unsigned short index = 0;
  while (input_text[index]) {  // while char is not 0 ('\0')
    input_text[index] = toupper(input_text[index]);
    index++;
  }
  printf("changed input_text: `%s`\n", input_text);
  return 0;
}

Visualize execution

C++ Strings

Use C++ strings instead of C strings unless there is a good reason otherwise.

C++ strings are a large and complex topic.
Fortunately, high quality documentation exists:

Questions
and feedback...