In lesson 4.4b -- An introduction to std::string, we defined a string as a collection of sequential characters, such as “Hello, world!”. Strings are the primary way in which we work with text in C++, and std::string makes working with strings in C++ easy.
Modern C++ supports two different types of strings: std::string (as part of the standard library), and C-style strings (natively, as inherited from the C language). It turns out that std::string is implemented using C-style strings. In this lesson, we’ll take a closer look at C-style strings.
C-style strings
A C-style string is simply an array of characters that uses a null terminator. A null terminator is a special character (‘\0’, ascii code 0) used to indicate the end of the string. More generically, A C-style string is called a null-terminated string.
To define a C-style string, simply declare a char array and initialize it with a string literal:
1 |
char myString[]{ "string" }; |
Although “string” only has 6 letters, C++ automatically adds a null terminator to the end of the string for us (we don’t need to include it ourselves). Consequently, myString is actually an array of length 7!
We can see the evidence of this in the following program, which prints out the length of the string, and then the ASCII values of all of the characters:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <iostream> #include <iterator> // for std::size int main() { char myString[]{ "string" }; const int length{ static_cast<int>(std::size(myString)) }; // const int length{ sizeof(myString) / sizeof(myString[0]) }; // use instead if not C++17 capable std::cout << myString<< " has " << length << " characters.\n"; for (int index{ 0 }; index < length; ++index) std::cout << static_cast<int>(myString[index]) << " "; std::cout << '\n'; return 0; } |
This produces the result:
string has 7 characters. 115 116 114 105 110 103 0
That 0 is the ASCII code of the null terminator that has been appended to the end of the string.
When declaring strings in this manner, it is a good idea to use [] and let the compiler calculate the length of the array. That way if you change the string later, you won’t have to manually adjust the array length.
One important point to note is that C-style strings follow all the same rules as arrays. This means you can initialize the string upon creation, but you can not assign values to it using the assignment operator after that!
1 2 |
char myString[]{ "string" }; // ok myString = "rope"; // not ok! |
Since C-style strings are arrays, you can use the [] operator to change individual characters in the string:
1 2 3 4 5 6 7 8 9 10 |
#include <iostream> int main() { char myString[]{ "string" }; myString[1] = 'p'; std::cout << myString << '\n'; return 0; } |
This program prints:
spring
When printing a C-style string, std::cout prints characters until it encounters the null terminator. If you accidentally overwrite the null terminator in a string (e.g. by assigning something to myString[6]), you’ll not only get all the characters in the string, but std::cout will just keep printing everything in adjacent memory slots until it happens to hit a 0!
Note that it’s fine if the array is larger than the string it contains:
1 2 3 4 5 6 7 8 9 |
#include <iostream> int main() { char name[20]{ "Alex" }; // only use 5 characters (4 letters + null terminator) std::cout << "My name is: " << name << '\n'; return 0; } |
In this case, the string “Alex” will be printed, and std::cout will stop at the null terminator. The rest of the characters in the array are ignored.
C-style strings and std::cin
There are many cases where we don’t know in advance how long our string is going to be. For example, consider the problem of writing a program where we need to ask the user to enter their name. How long is their name? We don’t know until they enter it!
In this case, we can declare an array larger than we need:
1 2 3 4 5 6 7 8 9 10 11 |
#include <iostream> int main() { char name[255]; // declare array large enough to hold 255 characters std::cout << "Enter your name: "; std::cin >> name; std::cout << "You entered: " << name << '\n'; return 0; } |
In the above program, we’ve allocated an array of 255 characters to name, guessing that the user will not enter this many characters. Although this is commonly seen in C/C++ programming, it is poor programming practice, because nothing is stopping the user from entering more than 255 characters (either unintentionally, or maliciously).
The recommended way of reading C-style strings using std::cin
is as follows:
1 2 3 4 5 6 7 8 9 10 11 12 |
#include <iostream> #include <iterator> // for std::size int main() { char name[255]; // declare array large enough to hold 255 characters std::cout << "Enter your name: "; std::cin.getline(name, std::size(name)); std::cout << "You entered: " << name << '\n'; return 0; } |
This call to cin.getline() will read up to 254 characters into name (leaving room for the null terminator!). Any excess characters will be discarded. In this way, we guarantee that we will not overflow the array!
Manipulating C-style strings
C++ provides many functions to manipulate C-style strings as part of the <cstring> library. Here are a few of the most useful:
strcpy() allows you to copy a string to another string. More commonly, this is used to assign a value to a string:
1 2 3 4 5 6 7 8 9 10 11 |
#include <cstring> int main() { char source[]{ "Copy this!" }; char dest[50]; std::strcpy(dest, source); std::cout << dest << '\n'; // prints "Copy this!" return 0; } |
However, strcpy() can easily cause array overflows if you’re not careful! In the following program, dest isn’t big enough to hold the entire string, so array overflow results.
1 2 3 4 5 6 7 8 9 10 11 |
#include <cstring> int main() { char source[]{ "Copy this!" }; char dest[5]; // note that the length of dest is only 5 chars! std::strcpy(dest, source); // overflow! std::cout << dest << '\n'; return 0; } |
Many programmers recommend using strncpy() instead, which allows you to specify the size of the buffer, and ensures overflow doesn’t occur. Unfortunately, strncpy() doesn’t ensure strings are null terminated, which still leaves plenty of room for array overflow.
In C++11, strcpy_s() is preferred, which adds a new parameter to define the size of the destination. However, not all compilers support this function, and to use it, you have to define __STDC_WANT_LIB_EXT1__ with integer value 1.
1 2 3 4 5 6 7 8 9 10 11 |
#define __STDC_WANT_LIB_EXT1__ 1 #include <cstring> // for strcpy_s int main() { char source[]{ "Copy this!" }; char dest[5]; // note that the length of dest is only 5 chars! strcpy_s(dest, 5, source); // A runtime error will occur in debug mode std::cout << dest << '\n'; return 0; } |
Because not all compilers support strcpy_s(), strlcpy() is a popular alternative -- even though it’s non-standard, and thus not included in a lot of compilers. It also has its own set of issues. In short, there’s no universally recommended solution here if you need to copy C-style string.
Another useful function is the strlen() function, which returns the length of the C-style string (without the null terminator).
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#include <iostream> #include <cstring> #include <iterator> // for std::size int main() { char name[20]{ "Alex" }; // only use 5 characters (4 letters + null terminator) std::cout << "My name is: " << name << '\n'; std::cout << name << " has " << std::strlen(name) << " letters.\n"; std::cout << name << " has " << std::size(name) << " characters in the array.\n"; // use sizeof(name) / sizeof(name[0]) if not C++17 capable return 0; } |
The above example prints:
My name is: Alex Alex has 4 letters. Alex has 20 characters in the array.
Note the difference between strlen() and std::size(). strlen() prints the number of characters before the null terminator, whereas std::size (or the sizeof() trick) returns the size of the entire array, regardless of what’s in it.
Other useful functions:
strcat() -- Appends one string to another (dangerous)
strncat() -- Appends one string to another (with buffer length check)
strcmp() -- Compare two strings (returns 0 if equal)
strncmp() -- Compare two strings up to a specific number of characters (returns 0 if equal)
Here’s an example program using some of the concepts in this lesson:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
#include <cstring> #include <iostream> #include <iterator> // for std::size int main() { // Ask the user to enter a string char buffer[255]; std::cout << "Enter a string: "; std::cin.getline(buffer, std::size(buffer)); int spacesFound{ 0 }; int bufferLength{ static_cast<int>(std::strlen(buffer)) }; // Loop through all of the characters the user entered for (int index{ 0 }; index < bufferLength; ++index) { // If the current character is a space, count it if (buffer[index] == ' ') ++spacesFound; } std::cout << "You typed " << spacesFound << " spaces!\n"; return 0; } |
Note that we put strlen(buffer)
outside the loop so that the string length is only calculated once, not every time the loop condition is checked.
Don’t use C-style strings
It is important to know about C-style strings because they are used in a lot of code. However, now that we’ve explained how they work, we’re going to recommend that you avoid them altogether whenever possible! Unless you have a specific, compelling reason to use C-style strings, use std::string (defined in the <string> header) instead. std::string is easier, safer, and more flexible. In the rare case that you do need to work with fixed buffer sizes and C-style strings (e.g. for memory-limited devices), we’d recommend using a well-tested 3rd party string library designed for the purpose, or std::string_view
, which is covered in the next lesson, instead.
Rule
Usestd::string
or std::string_view
(next lesson) instead of C-style strings.
![]() |
![]() |
![]() |
I have a program that I need to make. It looks for a specific character in a long text and prints how many times it was used. I can check if the program is OK online on the website ( it uses a C++11 / C++14 compiler). The programs works, but I get another problem "Time Limit Exceeded". It takes about a second for the program to run and I need it to be faster. Do you have any idea what could help out? Thanks in advance.
Formatted extraction via `operator>>` and `std::strlen` are slow.
Your code is unsafe, as `word` will overflow if a word is longer than 20 characters.
`operator>>` can be replaced with `read()`, which doesn't do any formatting.
`std::strlen` is unnecessary, you know how long your buffer is.
You can play around with the buffer size. Larger buffers should be faster. This code should be at least twice as fast as yours.
A few minor typos:
"An" should be "A":
"compiler" should be "compilers":
"Because not all compiler support strcpy_s()"
"it's" should be "its":
"It also has it’s own set of issues."
Thanks for a great resource!
Typos fixed. Thanks!
"Because not all compiler support strcpy_s()..."
I do not have strcpy_s (). I thought standard libraries are the same. But it looks like someone add new functionality to a standard library and someone else do not.
The C++ standard defines some functions and types that are optional. Implementations with and without those entities are both valid. To guarantee that your code works everywhere, avoid those entities altogether unless you provide alternatives.
To be even more confusing ...
I have Arch Linux on 64 bit, CodeBlocks (using clang or gcc).
If I use CodeBlocks, I can use std::size() (from <iterator> header) with both clang and gcc.
If I use the terminal with clang++ or g++, std::size() (from <iterator> header) is not found or something like that.
But CodeBlocks use the same clang (or gcc) that is installed on Arch Linux... 0_O
You need to tell clang which standard to use
Why is sizeof () always the same? On my system 32.
sizeof (<some_structure_identifier_here>) gives me the size of that structure in bytes, but this is not the case with std::string objects.
`std::string` stores a pointer to the char array, it doesn't store the string directly. You'll understand it by the end of this chapter.
This is somehow unexpected for a beginner, because sizeof (arr) (where arr is a fixed array) gives the whole size of the array. Even if arr decays to a pointer. Maybe because it would be almost useless to give the size of a pointer, and more valuable to give the whole size of the array. But then sizeof (std::string) being always the same, it looks like it is also useless. Or maybe don't. So many little details in C++. :)
> Even if arr decays to a pointer
No. `sizeof(arr)` returns the size of the pointer if the array decayed.
`sizeof` is supposed to give you the size of the data type, and that's what it's doing. If you want to know something type-specific, eg. string length, you should use the functions provided by that type (std::string::length).
You only need `sizeof` if you're doing operations on the raw data. Use `std::size` for arrays.
Is this better? Here strlen () is not called and executed for every iteration.
Yes. If the condition is expensive (`std::strlen` has to loop through the string on every call) and doesn't change, you should store it in a temporary.
Instead of 'strcpy()', why not just 'source = dest'?
You'd copy the pointer, not the string. Pointers are covered in the next few lessons.
Hi,
I have a quick question. Say I was writing code to play a game of hangman.
I'm guessing for that game, I will need to compare every single letter of a word.
How would I do this using std::string?
Thanks!
Use a for-loop. Since you didn't post any code, this is what I suppose you're stuck at
I don't want to spoil you, so I'm not posting the rest of the code. If you have another question, feel free to ask. If you just want to see the start of 1 possible implementation without trying yourself, have a look here
https://godbolt.org/z/jB60I6
Hi thanks for responding!
I am not really coding that game, it was just an example in my mind.
I was wondering how to look at the single letters in a string without c-style strings.
And to be honest, I don't get most of your example.
I'm guessing std::string::size_type is a special type of string?
and if strSolution is the word in std::string type then what is strSolution.length()? is it just the length of that word?
Are you jumping letter with ui?
Is this material explained later in this tutorial?
Thanks!
Chapter 17 is all about `std::string`. (Watch out, it's an old chapter with bad practices).
`std::string::size_type` is the type used by `std::string` for indexing. It's some unsigned integer type.
`std::string::length` (same as `std::string::size`) returns the length of the string.
"Hello" -> 5
"BP" -> 2
ui starts at 0 and goes all the way up to the string's length minus 1. For example, given the string "Hello", ui goes 0, 1, 2, 3, 4. (5 is an invalid index).
`std::string`'s individual characters can be accessed just like those of a C-style string, using `str[index]`.
So since I still need to learn lot's or stuff before chapter 17, I thought I would just for the fun of it try using C-style strings for hangman.
It is a bit ugly, and spaghetti like, but here is my attempt.
I hope it is a bit ok...
Thanks for all your help!
The only place where you used a C-style string is line 63, which is only required for the fixed-size array. Other than that your code is already using `std::string`.
You should be able to understand chapter 17, I don't know why Alex decided to wait until the end.
Some suggestions:
- Limit your lines to 80 characters in length for better readability on small displays.
- Line 19+: I don't think char extraction can fail.
- Line 69: That `false` doesn't do anything. The entire array is initialized to `false` by using empty curly brackets.
- Line 98 has no effect. `lettersGuessed` isn't used after here.
- You could remove the "word"/"letter" test by always reading a string and checking its length. If it's 1, you run the letter code. If it's > 1, you run the word code.
How would I check the length of a array if it's size should be fixed?
It doesn't matter what I put in the machine the size is fixed.
I guess this can be solved by using non fixed arrays?
I'll probably see those in a few chapters.
Thanks again for your pointers!
`std::string` is dynamic, ie. it's length is not known at compile-time, so you'd have to use a dynamically allocated array (Covered later in this chapter).
The core lessons of this tutorial are focused on broad understanding. Originally, the lessons at the end were going to be a deeper dive into some of the more common classes of the standard library -- but I didn't get far in that approach.
#include <iostream>
int main()
{
char name[2]; // declare array large enough to hold 255 characters
std::cout << "Enter your name: ";//mangesh
std::cin.getline(name, 3);
std::cout << "You entered: " << name << '\n';
return 0;
}
Thank you so much for this wonderful tutorial! I finally feel I can learn c++!
My question is the following: I wanted to change the value of one element of the string as:
char ss[] = "feast";
ss[0] = "b";
std::cout << ss;
which gives me the error: invalid conversion from 'const char*' to 'char' [-fpermissive]|
but when I switch it to:
ss[0] = 'b';
everything compiles fine. Why?
"b" is a char array (const char *)
'b' is a char (char)
ss[0] is a char
You can't assign a char array to a char.
Hello and good morning,
why does an array outputs its address when we're using array(itself, without braces), and @string which is C-style string does not ?!
Skim below to understand.
Arrays decay into pointers. @std::cout<< treats char pointers as strings.
So the difference between C-style strings and arrays is that @std::cout treats them different, ok?
And they all are arrays with different type.
Right ?!
right
I have a question. How come when you overflow the array (the example with strcpy()), it still prints out the array as it should (I can print out the string in the dest same as in the source)? The length of the dest (strlen) after copying is equal to the actual length of the dest + the length of the string that was copied, but the sizeof dest still returns declared length of the string. Is this dependent on the machine and/or the compiler? (Windows 7x64 and Code::Blocks 17.12) Does the compiler allocate the array dynamically? Also, what happens with the strlen, why is it the original length + lenght of the copied string, not just the length of the copied string OR the original length? Thank you for your time
@std::strcpy doesn't check bounds, it copies as much as you tell it to. If you tell it to write to memory you're not supposed to access, behavior is undefined.
@sizeof returns the length you declared the array with, it can't change at run-time.
@std::strlen loops through the string until it finds the 0-terminator. Again, without bounds checks, if it accesses memory after the reserved length, behavior is undefined.
Oh, ok, so if I got it right, it is a matter of pure luck if the program will output what we gave it if we write out of bounds? Like, if some other program overwrites the memory we accesed by going out of bounds, and wrote over the /0 terminator, the program will keep outputing random garbage, untill it, by chance, finds first /0 terminator?
Thanks for the answer :)
> some other program overwrites the memory we accesed
That can't happen, at least not on the major OSs. But other variables or code in your program could conflict with the memory you're trying to access.
@std::cout prints everything until it finds the 0-terminator, or your program crashes, because it's accessing memory which it's not allowed to access, whichever comes first.
Thanks for clearing that up
When I try to convert std::size(array) into an integer type, vb gives me an error and says that in order to convert from 'size_t' to' int' I need to do a narrowing conversion. However in your code you did not have to do a narrowing conversion. I changed my c++ version to c++17, and also tried changing it to the latest update, but the error message still came up. Could anyone please explain this to me? Thanks
Use a @static_cast.
Narrowing conversions usually cause a warning, you probably set your compiler up to treat warnings as errors (This is a good thing).
Hello, can you please help me with this code:
The problem is, when I read the string from the file, it repeats a character at the end.
e.g. If I store "welcome" in the file, it prints "welcomee" on the screen although the file contains the string "welcome".
* Line 8, 9, 12, 22: Initialize your variables with brace initializers.
* Line 23: Booleans are false/true.
* Line 14-19: Should be a for-loop.
* Don't use "using namespace".
* Missing printed trailing line feed.
* Line 18: Use ++prefix unless you need postfix++.
* Magic number: 80. Use @std::size.
You're not writing a null-terminator to the file.
Ok thanks Nascar!
What I wonder now is this... Is there a way to convert a C-string into a std::string and vice versa.... Like this pseudo code:
I'm not sure if I would ever actually need this, but just in case ;)
std::
why its important ??
https://www.learncpp.com/cpp-tutorial/naming-conflicts-and-the-std-namespace/
The first line only supports C style string variable as its first argument.
The second line only supports string variable as its second argument.
Are the getline functions same in both lines.
I am confused with it.
Hi Piyush!
They're not the same, but they behave the same, use whichever you prefer, the second is easier to use since you don't need to know the length beforehand.
Thanks for the reply