Like Tree2Likes
  • 2 Post By CornedBee

C-strings Vs Strings in C++

This is a discussion on C-strings Vs Strings in C++ within the C++ Programming forums, part of the General Programming Boards category; Hey all, first post. So, i'm a newbie and working my way through C++ without fear. I've noticed that through ...

  1. #1
    Registered User
    Join Date
    Jul 2011
    Posts
    22

    C-strings Vs Strings in C++

    Hey all, first post.

    So, i'm a newbie and working my way through C++ without fear. I've noticed that through the book the author has been declaring and intializing string variables in this way

    char *new_string = "Freem";

    I've got to the chapter on strings and have noticed that there is a lot of emphasis on c-strings and not the 'new' string type which declares and initializes like this.

    string new_string = "Freem";

    I've used java a little bit in the past and pre-C++ without fear have done have always used the 'new' string type.

    What is the benifits of c-strings. I like the new string type and feel comfortable with it - should i continue with that or should i stop and start using the c-strings?

    Thanks in advanvce

  2. #2
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,761
    I consider the std::string type to be superior. That doesn't excuse not knowing about character arrays, but you should use std::string as much as you can (or some other string object). In particular, C-strings are good to know about because you'll encounter them, regardless, and some methods like fstream::open() actually use C-strings.

  3. #3
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,893
    Code:
    char *new_string = "Freem";
    C-string vs std::string aside, this is just plain wrong. (Well, deprecated. But still wrong.)
    Never assign a string literal to a pointer to non-const. The correct way to write this is:
    Code:
    const char *new_string = "Freem";
    Elysia and iMalc like this.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  4. #4
    Registered User
    Join Date
    Jul 2011
    Posts
    10
    Char arrays can be useful in some ways, strings are quicker to use.

  5. #5
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    The only thing I find much less awkward with c-strings is reading different data types in or out; what you can do in one simple line with sscanf/sprintf, done with std::string requires a new object (a stringstream) plus repeated, separate calls to its methods for setting precision, field width, etc, and adding/extracting one item at a time. Even so, when working in C++ I use std::string except where impossible.

    Conversely, std::string is a lot less awkward for working with data of arbitrary and uncertain length.

    Other than that, I don't find them very different. You probably do have to learn both of them anyway because there are many basic situations that require one but not the other.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  6. #6
    Registered User
    Join Date
    Aug 2010
    Location
    Poland
    Posts
    682
    Quote Originally Posted by MK27 View Post
    Conversely, std::string is a lot less awkward for working with data of arbitrary and uncertain length.

    Other than that, I don't find them very different. You probably do have to learn both of them anyway because there are many basic situations that require one but not the other.
    C-strings are pure arrays while std::strings are object-oriented, what makes them two totally different interfaces.

    std::(w)string should always be prefered, unless there is a specific reason.
    Last edited by kmdv; 07-05-2011 at 01:28 PM.
    I never put signature, but I decided to make an exception.

  7. #7
    Registered User
    Join Date
    Aug 2010
    Location
    Poland
    Posts
    682
    Quote Originally Posted by CornedBee View Post
    C-string vs std::string aside, this is just plain wrong. (Well, deprecated. But still wrong.)
    Never assign a string literal to a pointer to non-const. The correct way to write this is:
    Code:
    const char *new_string = "Freem";
    I know it is true, however, I have found an example in the C++0x standard with such an assignment.
    Have a look at the example in 9.5.5 (unions), it says:

    Code:
    void f() {
    union { int a; char* p; };
    a = 1;
    p = "Jennifer";
    }
    Could somebody explain it to me?
    I never put signature, but I decided to make an exception.

  8. #8
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by kmdv View Post
    C-strings are pure arrays while std::strings are object-oriented, what makes them two totally different interfaces.
    Yes but that is a very superficial syntactical difference, IMO, and I am perfectly comfortable with both "interface styles", so that is more or less a non-issue (for me, and probably lots of other people too):

    Code:
    doSomething(myArray, param);  // array function syntax.
    myObject.doSomething(param);  // OO syntax, OMG.
    std:w)string should always be prefered, unless there is a specific reason.
    Agreed, and I said that explicitly. "Specific reason" to me is usually: low level C API making it impossible to not use a c-string at various points, in which case I am not going to turn a char* returned into a std:string then turn it back into a c_str() as it is passed around, that is like driving in concentric circles toward your destination. I recognize there are some C++ wrapper API's that do more or less exactly that, which is why I said: you might as well learn both of them so you do not have to depend on wasting resources to work around your weaknesses.

    Quote Originally Posted by kmdv View Post
    p = "Jennifer";
    Could somebody explain it to me?
    Since "a" is not const and it is a union there is no point in "p" being const.
    Last edited by MK27; 07-05-2011 at 01:47 PM.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  9. #9
    Master Apprentice phantomotap's Avatar
    Join Date
    Jan 2008
    Posts
    4,405
    Code:
    doSomething(myArray, param);  // array function syntax.
    myObject.doSomething(param);  // OO syntax, OMG.
    O_o

    Syntax has nothing to do with design methodologies.

    You can't tell if either or both of those lines invoke some "OOP" construct.

    The first call could just as easily be "OOP" using strait C interfaces.

    The second call just as easily be an "I'll just put this here for my convenience." situation where `??? doSomething(???)' represents a function pointer.

    In the case of `std::string' versus `char *', the argument could be made for syntax differences, but that isn't what makes it "OOP" or not. The `std::string' object maintains state and supports methods that mutate that state. The `char *' version has state and functions that mutate that state. The difference is that the `std::string' object maintains more state that is relevant to the nature of the construct it represents than the `char *' version. For example, the `std::string' object automatically mutates the associated length of the string. The `char *' version does not maintain such additional state. A C programmer could easily wrap a `char *' up with a structure and create a few functions that operate on that structure to maintain similar state. The necessary syntax differences of the C version doesn't magically imply that the resulting structure and operations are not following "OOP" principles.

    So, yea, your logic here is just as bad as the "OOP" purists who think free functions break "OOP" principles.

    Friendly and powerful syntax is nice and extremely useful, but syntax alone doesn't make a thing conform to principles and methodologies of a programming "paradigm".

    Soma

  10. #10
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Posts
    23,002
    Quote Originally Posted by MK27 View Post
    ...Agreed, and I said that explicitly. "Specific reason" to me is usually: low level C API making it impossible to not use a c-string at various points, in which case I am not going to turn a char* returned into a std:string then turn it back into a c_str() as it is passed around, that is like driving in concentric circles toward your destination...
    Just pointing out that you can replace char arrays with std::vector and avoid C-style strings altogether. It works great for when you need dynamic length C-style strings (ie buffers).

    Quote Originally Posted by MK27 View Post
    The only thing I find much less awkward with c-strings is reading different data types in or out; what you can do in one simple line with sscanf/sprintf, done with std::string requires a new object (a stringstream) plus repeated, separate calls to its methods for setting precision, field width, etc, and adding/extracting one item at a time...
    Boost.Format fixes that (out)! It's a shame there's no such thing in the standard, though.
    And boost::lexical_cast fixes type conversions for many things. Reading in specific types can already be done with std::cin >>.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  11. #11
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,893
    Quote Originally Posted by kmdv View Post
    I know it is true, however, I have found an example in the C++0x standard with such an assignment.
    Have a look at the example in 9.5.5 (unions), it says:

    Code:
    void f() {
    union { int a; char* p; };
    a = 1;
    p = "Jennifer";
    }
    Could somebody explain it to me?
    Interesting. Especially since the C++03 standard already contains exactly this example. Once I get my main computer back I can check the FDIS (they've since locked it down). Anyway, this should be submitted as an editorial defect.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  12. #12
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    22,265
    Quote Originally Posted by CornedBee
    Once I get my main computer back I can check the FDIS (they've since locked it down). Anyway, this should be submitted as an editorial defect.
    In the FDIS, p is now const char*, not char*
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  13. #13
    Master Apprentice phantomotap's Avatar
    Join Date
    Jan 2008
    Posts
    4,405
    I think that has been fixed for a while. The latest draft I have is from February; it is fixed in that draft.

    they've since locked it down
    I know you can get the latest draft papers with draft numbers and difference formatting, but I didn't know they ever released "FDIS" level papers with "FDIS" formatting. (Though from what I'm told, the latest draft equivalent is exactly the same as the "FDIS" except where the markup noting the differences between drafts has been omitted.) It was my understanding that the practice was even against ISO rules.

    Soma

  14. #14
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,893
    N3290 is the FDIS, N3291 is the final draft. But now both of them are locked down. The most recent version you can get is N3242, which is what you have.
    But for a few weeks directly after the mailing was published, both N3290 and N3291 were freely available. This may have been just an admin mistake, but whatever.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Swapping strings in an array of strings
    By dannyzimbabwe in forum C Programming
    Replies: 3
    Last Post: 03-03-2009, 12:28 PM
  2. malloc() strings VS array strings
    By Kleid-0 in forum C Programming
    Replies: 5
    Last Post: 01-10-2005, 10:26 PM
  3. Table mapping Strings to Strings
    By johnmcg in forum C Programming
    Replies: 4
    Last Post: 09-05-2003, 12:04 PM
  4. converting c style strings to c++ strings
    By fbplayr78 in forum C++ Programming
    Replies: 6
    Last Post: 04-14-2003, 04:13 AM
  5. finding strings in strings
    By watshamacalit in forum C Programming
    Replies: 14
    Last Post: 01-11-2003, 01:08 AM

Tags for this Thread


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21