Why doesn't this work? (strings)

This is a discussion on Why doesn't this work? (strings) within the C++ Programming forums, part of the General Programming Boards category; Found this code inside accelerated c++...as an exercise.... I don't understand why the code does not work.. the bottom code... ...

  1. #1
    Registered User
    Join Date
    Jul 2002
    Posts
    31

    Why doesn't this work? (strings)

    Found this code inside accelerated c++...as an exercise....
    I don't understand why the code does not work.. the bottom code...
    It gives the following error

    8 c:\docume~1\pier\mydocu~1\sc103\lab4\untitl~1.cpp
    invalid operands `const char[6]' and `const char[7]' to binary `operator +'

    Pier.

    Code:
    #include <iostream>
    #include <string>
    
    int main(void) {
        /*const string hello = "Hello";
        const string message = hello + ", world" + "!"; */ //works
        const string exclam = "!";
        const string message = "Hello" + ",world" + exclam;
    
        return 0;
    }

  2. #2
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,789
    You are redefining an object....also you cant use operator+ for 2 strings like that....strings are in namepsace std....once you mark something const, you cant redefine it


    Code:
    #include <iostream>
    #include <string>
    using namespace std;
    
    int main(void) {
        const string hello = "Hello";
        const string message = hello + ", world";
        const string exclam = "!";
        
        cout << message <<  exclam;
    
        return 0;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 04-29-2009, 10:13 AM
  2. Strings Program
    By limergal in forum C++ Programming
    Replies: 4
    Last Post: 12-02-2006, 02:24 PM
  3. Problem with Strings, Please help!
    By varus in forum C++ Programming
    Replies: 8
    Last Post: 11-27-2006, 10:47 PM
  4. The Bludstayne Open Works License
    By frenchfry164 in forum A Brief History of Cprogramming.com
    Replies: 8
    Last Post: 11-26-2003, 10:05 AM
  5. Table mapping Strings to Strings
    By johnmcg in forum C Programming
    Replies: 4
    Last Post: 09-05-2003, 11:04 AM

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