Reputation: 873
I have seen tutorials that are using an array of characters in order to demonstrate something with a string object. For example thees tutorials:
http://www.cplusplus.com/reference/string/string/copy/
http://www.cplusplus.com/reference/clibrary/cstdlib/atoi/
I HAVE seen tutorials that are not using a char array in order to demonstrate something. At school, the teacher also doesn't use any arrays. For me, using an array is a bit confusing at first when I'm reading the tutorial (knowing that I'm still a beginner at C++).
I'm just curious to know why are there tutorials that use a char array in order to show one or more of the things that string objects can do.
Upvotes: 2
Views: 339
Reputation: 900
See the Bjarne Stroustrup's paper "Learning Standard C++ as a New Language" www2.research.att.com/~bs/new_learning.pdf
Upvotes: 1
Reputation: 25337
In C and C++ strings are/were unusually represented as '\0'
terminated arrays of char
. With C++ you can use the standard class string
, but that is by no means a "natural" thing to do, when representing strings. Many C and C++ programs are still quite content using an array of char
.
Upvotes: 2
Reputation: 3875
Strings appeared when the STL appeared, when the C++ standard was formed somewhere in the 1990s if i remember well. Until then (for example Turbo C++ which is still used at my school... unfortunately), there was no 'string' object in C++, so everyone used char arrays. They are still widely used, because strings don't really introduce many new things that char arrays can't do, and many people don't like them. Strings are in fact null ended char arrays, but they hide this behind a class.
One problem with strings is that not all library functions support them. For example, the printf family of functions, atoi (which comes from 'ascii to integer', also atof and all the others), these don't support strings. Also, in larger projects, sometimes you need to work in C, and strings don't exist in C, only char arrays.
The good thing about strings is that they are implemented in such a way that it is very easy to convert from and to char arrays.
Upvotes: 0
Reputation: 6526
Storing strings in arrays of characters was the original way to represent a string in the C language. In C, a string is an array of type char. The size of the array is the number of characters, + 1. The +1 is because every string in C must end with a character value of 0. This the NULL terminator or just the terminator.
C-style strings are legal in C++ because C++ is intended to be backwards compatible with C. Also, many library and existing code bases depend on C-style string.
Here is a tutorial on C-style strings. http://www.cprogramming.com/tutorial/c/lesson9.html
FYI: To convert a C++ String to a C-style string, call the method c_str().
Upvotes: 6