char[] vs string

Pages: 12
Dec 9, 2021 at 4:06pm
In various places and code snippets, I see some people use strings, and some people use char arrays. I get the sense that the string object was created for newer programmers, while older programmers prefer to use char[].

I'm curious if it is somewhat frowned upon to use string in C++? If so, why?
Dec 9, 2021 at 4:18pm
Older programmers prefer to use char[] because their brains are less plastic.

You should use std::string unless you have a specific reason not to. You might need to use char[] if you're working with C-style interfaces or interop stuff.
Last edited on Dec 9, 2021 at 4:19pm
Dec 9, 2021 at 4:31pm
char [] is from C. It's an array of char. std::string is a C++ class type that provides many advantages over char[] and should be used unless a type of char[] is required eg for a C function param etc.
Dec 9, 2021 at 4:40pm
SlowCoder wrote:
...frowned upon to use string in C++?

Absolutely not! C++ code, use std::string. Should you need a char[] array, use std::string::c_str.

http://www.cplusplus.com/reference/string/basic_string/c_str/

Ganado wrote:
Older programmers prefer to use char[]

Hey now! I may be old, been self-learning C++ solo since before C++98, but I very much prefer std::string over a C string char[] array. :Þ

Even younglings can use stone knives and bear skins instead of modern tools. It is what, and how, they were taught. In many cases mis-taught.

<rant>

Classic example, continuing to use the C library's random number functions instead of what C++ has to offer.

Or regular arrays instead of C++ containers like std::vector.

</rant>
Dec 9, 2021 at 4:52pm
@Furry Guy. Ganado didn't write that. He was just quoting the OP. It was SlowCoder that wrote that.
Dec 9, 2021 at 4:53pm
It's not a matter of old verses new programmers. It's an issue of C programmers verses C++ programmers. As others have said, there's little reason to use char[] in C++. From posts here, I get the sense that a lot of teachers of C++ expect students to use char[] before introducing std::string.

By the same token, C programmers use arrays, while C++ programmers use std::vector or other suitable containers.
Dec 9, 2021 at 5:02pm
a lot of teachers of C++ expect students to use char[] before introducing std::string.

I'm kinda the opposite, teach beginners C++ constructs like std::string first. If'n they want to continue learning then by all means throw in C string char[] arrays later.

@seeplus, Initial capitalization makes ALL the difference. Older vs. older. Ooops!
Dec 9, 2021 at 5:11pm
Ill be the curmudgeon here :)
I love sprintf. Period. I find having 3 *THREE* objects to do the same thing (stringstream, string, and stringview) somewhat moronic. I get why we ended up there, but I still hate it.

apart from sprintf, though, std::string is a lot easier to use outside of one or two additional edge cases where c style strings are superior.
The other cases I run into on occasion are
1) strstr. find() is close, but find() is not boolean, strstr is(indirectly). Sometimes, I want to know if its there or not, without caring where etc. find is clunky and wordy for that.
and
2) 'destructive parsing / splitting'. This is where you replace say spaces with zeros and pull pointers to split a string into 'words'. You can't do that with string easily.

even so its been a while since I felt a need to use C style strings. A lot of external interfaces (files and networking, devices, more) DO use c style strings, but for that you can just pull a .cstr() and send it out.

String ... was put in too late. At the time it came out there were at least 3 or 4 major string objects in play, and it while it was meant to consolidate it really was just another on the pile for a while, because rewriting all that stuff to use it was too much. Using it in new code was a great goal but MFC wants its C string wrapper thingys and won't play nice with it, and that too was an issue for a while until .net came along and its still an issue if you use the old tools (some still do, its supported etc).

All that aside, use string, but learn enough about c style strings to function if you run into something that won't play nice with the object.
Last edited on Dec 9, 2021 at 5:25pm
Dec 9, 2021 at 5:17pm
I love sprintf.

Until C++20 formatting text was hard to do. std::format kinda changed that.

https://en.cppreference.com/w/cpp/utility/format/format

Dec 9, 2021 at 5:34pm
yes, that is a major upgrade.
but now you are looking at 20+ years of habit to break for people like me, because they forgot to put it in back in 98. Its a welcome change, but taking 20 years for what should have been a day 1 tool is mind blowing to me. And look at the complexity required for their little example... /choke. I haven't studied it enough to see if that is just bad code or if it really needs all that to function, but ... it just can't take that much gibberish to do what C has done since 1980. It just can't be that hard.
Last edited on Dec 9, 2021 at 5:42pm
Dec 9, 2021 at 5:42pm
Wow, lots of quick replies! And I can see that I got some "facts" wrong in my OP. Thank you all for politely, sometimes humorously, and very knowledgeably correcting me!

I wanted to ensure I was using best C++ practices coming out the gate as I learn.

Coming from C#, it's been mostly strings, and very rare to use char. I'll be sure to continue that practice in C++.
Dec 9, 2021 at 5:49pm
C# has newtons' advantage.... it stood on the shoulders of giants when it came to be.
Dec 9, 2021 at 6:03pm
@jonnin, I can't argue about the timing of the addition of either std::format or std::string. They are now a part of the standard library, though, and so should be used.

I do quibble with you, courteously, saying std::stringstream, std::string and std::string_view "do the same thing".

std::stringstream implements input and output operations on string based streams. Are std::string and std::cin or std::cout the same? No. std:stringstream and std::cin/std::cout are quite similar, though. About the only difference is the stream's origin.

Now, std::string and std::string_view are quite similar. The performance between the two in several areas is why (at least IMO) std::string_view was added.

std::string_view::substr being one major difference in complexity over what std::string has.

https://dzone.com/articles/performance-of-stdstring-view-vs-stdstring-from-c1

SlowCoder wrote:
Coming from C#

Oh, ICKERS! You got a lot of bad, Microsofty, habits to break! :D

Seriously, if I were you I'd try to forget most everything you learned about C# and plow into C++ as if it was your first programming language. C# is not C or C++.

Learn C++ is a free resource to help teach C++ from the ground up:

https://www.learncpp.com/

cppreference is a free reference resource, it is kept as up to date as possible but it is NOT a site you can learn C or C++ from.

https://en.cppreference.com/w/

Dec 9, 2021 at 6:06pm
I wrote what I wrote! Was just a lighthearted joke :)
Dec 9, 2021 at 6:09pm
ah, no, what i meant was stringstream does what sprintf did, except it has all the clunk of streams to format (width, # of decimals, etc). If they wanted this, then why not just apply << operator to string directly, why 2 objects? And stringview .. I dunno if it belongs in string, maybe, but it certainly could have been better as a set of static functions instead of yet another full object.
As you said, its in there, and should be used now. But .. what a trainwreck.

maybe this will help see it from my warped world view :)
I want to put a double into a string, formatted my way, without any fuss.
fuss meaning notably more effort than "%width.digitsf"
::to_string ... oops, forgot to let you format it. << formatting is atrocious and takes an extra object. the new format thing, still can't drop directly into the target (or can you?!). I need to verify what it can and can't do in a line or two of code. Its like the simplest, most common thing a person might want to do is one of the most convoluted.
Last edited on Dec 9, 2021 at 6:18pm
Dec 9, 2021 at 6:09pm
Ganado wrote:
I wrote what I wrote! Was just a lighthearted joke :)

And I wrote my reply to YOU in the same vein. Joking about being called "old". :)

I even stuck my tongue out at ya! :Þ

Someone else, neither you nor me, just wanted to be grumpy.
Last edited on Dec 9, 2021 at 6:29pm
Dec 9, 2021 at 6:13pm
I was replying to seeplus :) I should use quotes more often.
Dec 9, 2021 at 6:30pm
Using quotes, Ganado, can be problematical as well, as we both can attest to. :D
Dec 9, 2021 at 7:22pm
(quick off-topic question: am I supposed to be able to quote a post in my replies? I don't see how to accomplish that. All I see are the report and link buttons in each post.)

@Furry Guy,
Yep, I'm sure there are many different dynamics I need to muddle through. But as my job is C#, I really can't just forget them.

Thanks for the link to learncpp.com. Looks like a good site (surprised I haven't run into it before.) I'm mostly figuring things out, but I'm a bit hung up on pointers and address-of operators. I think I just need practice. But that's a subject for another thread. ;)
Dec 9, 2021 at 7:51pm
SlowCoder wrote:
am I supposed to be able to quote a post in my replies?

No, you aren't required to quote another post, but as you can see it does help to reduce confusion.

Or add to the confubble when people seem to want to stir things up.

See the twelve format buttons at the right of the edit box? The one on the right at the top, the double quotes ("), is used to create a block using quote tags.

How to use code tags:
http://www.cplusplus.com/articles/jEywvCM9/

How to use tags in general, including code tags:
http://www.cplusplus.com/articles/z13hAqkS/

PLEASE read both links to familiarize yourself with what you can do using tags. :)

Using code tags is practically a must-use.

SlowCoder wrote:
I'm a bit hung up on pointers and address-of operators.

Wait until you get to subject of references.

Pointers are easy (relatively) in theory, but can be deucedly complicated in practice. C++ inherited pointers and address-of semantics from C, and added the concept of references to be less "weird."

Learn C++ has a nice introduction to pointers:
https://www.learncpp.com/cpp-tutorial/introduction-to-pointers/

I'd suggest you peruse ALL of chapter 10 to get a flavor of how much even in C pointers hide in the most unexpected place. Arrays, for example.

Understanding pointers and how they work are IMO very key to understanding how C++ does certain things. Most of the C++ containers, for example, use pointer-like constructs (called iterators) to be able to access the container's elements. A common interface for the container element access.
Pages: 12