Thread: Null character and string object

  1. #1
    Registered User
    Join Date
    Oct 2003

    Null character and string object

    Hi folks,

    Just a quick question: what is so illegal about the following line of code? That is, why would it throw an exception?

    std::string someStr='\0';
    If I define someStr first, and then assign the null character second, I have no problem. Why is this? Aren't the two equivalent, but I've just shifted the assignment down a bit?


  2. #2
    Registered User
    Join Date
    Sep 2003
    You can't initialise an std::string with a character in that way. If you really need to you should be able to do the following:

    std::string someStr(1,'\0');

    Note that in C++ initialisation and assignment are two very different things.

  3. #3
    Disturbed Boy gustavosserra's Avatar
    Join Date
    Apr 2003
    The assignment operator is overloaded to receive a string as parameter. Is like having a function:
    void f(char *str);
    and use it passing a char.
    Nothing more to tell about me...
    Happy day =)

  4. #4
    Registered User
    Join Date
    Oct 2003
    Omnius: Thankyou, what you told me coupled with a bit of research of my own answered my question.

    gustavosserra: That's true, but after reading the definition for std::string I found that it's also overloaded for char, which would explain why I had no problems assigning the character later.

    Thanks for the help, both of you. Much appreciated.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. New string functions
    By Elysia in forum C Programming
    Replies: 11
    Last Post: 03-28-2009, 05:03 AM
  2. String issues
    By The_professor in forum C++ Programming
    Replies: 7
    Last Post: 06-12-2007, 09:11 AM
  3. Replies: 4
    Last Post: 03-03-2006, 02:11 AM
  4. Please Help - Problem with Compilers
    By toonlover in forum C++ Programming
    Replies: 5
    Last Post: 07-23-2005, 10:03 AM
  5. lvp string...
    By Magma in forum C++ Programming
    Replies: 4
    Last Post: 02-27-2003, 12:03 AM