A C String is actually an array of characters. While C strings are a thing, generally speaking it is best to use the C++ string object. However, if you run into an older application, or someone who wants to do things old style, it is good to know how to use a C-String.
Additionally, any time you use a String Literal, C++ is using the C-String to use it, so you’ve been using them, without knowing you’ve been using them. You might be asking why, well, they are simpler, take less memory and processing power to use. The downside is they put more responsibilities on the programmer.
The last element of a C-String is a null character ('\0'
), always. This is how it knows to terminate the string.
char city1 = "Greeneville"; // C-String
char city2 = {'G','r','e','e','n','e','v','i','l','l','e'}; // not a C-String
Output
You can simply use the cout
statement to print data to the screen.
char data[] = "This is a sample string.";
cout << data << endl;
Input
You can use cin, but remember the issues with it and spaces. There is another option, similar to getline, that is cin.getline(). It’s a method and you have to pass it the size of your array. Remember to have an extra space for the null character.
So a 15 character string, needs to be sized 16. Always better to have a little extra room than not enough.
char data[16];
cout << "Enter your favorite food: ";
cin.getline(data, 16);
C-String Functions
Copying Data
Assigning data is normally simple with strings. However, a standard practice, like you see below will generate an error with C-Strings.
char data[] = "This is a sample string.";
data = "Another string"; // this is an error
cout << data << endl;
Instead you must use a function like strncpy()
or strcpy()
– string copy.
char data[] = "This is a sample string.";
strncpy( data, "Another string");
cout << data << endl;
Note: Visual Studio will not let you use strcpy as it is marked “unsafe” instead you will need to use strcpy_s().
strncpy specifies the number of characters to copy, strcpy copies the entire string.
To compare strings you need to use the strcmp()
function. It returns a 0 if they are equal, a negative value is string 1 is larger than string 2 and a positive value is string 2 is larger.
To convert strings to numbers, you can use atoi()
to convert a string to an integer, or atol()
to convert it to a long. Similarly atof()
will convert a string to a floating point numbers.
To convert a number to a string, you can use something like itoa()
, to convert an integer to an array of characters. In it, you must pass 3 parameters, the number, the character array to store the value in, and the size of the character array.
char string1[10];
int x = 350;
itoa(x, string1, 10);
You might be asking yourself why so many functions. Well, C didn’t have overloading. So it had to have separate functions for every time a parameter changed.
C-Strings in C++ was originally found on Access 2 Learn