Thread: String Error!!

  1. #1
    Registered User
    Join Date
    Sep 2002
    Posts
    10

    Unhappy String Error!!

    Hi,
    In the below code I've copied the value of a string variable into "store" (which is Char(50).
    When I print the value of store, it crashes!!!
    please can someone tell me how to store from string to char and print the value of char!!
    thanks
    John

    Code:
    ==============================================
    strcpy(store,ret.c_str());
    printf("%s",store);
    =============================================

  2. #2
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,793
    Code:
    #include <string>
    #include <cstdio>
    
    
    
    int main(){
    
    	char cstr[50] = {0};
    
    	std::string str("Hello World\n");
    
    	strcpy(cstr,str.c_str());
    
    	printf(cstr);
    	
    	return 0;
    }

  3. #3
    Registered User
    Join Date
    Nov 2001
    Posts
    1,348
    You have to end a string of characters with a NULL. Fordy initialized all elements in the array to NULL. That works too.

    Kuphryn

  4. #4
    Registered User
    Join Date
    Nov 2001
    Posts
    1,348
    A string object does not have a NULL by default. In fact, a string object could contain more than just characters.

    Kuphryn

  5. #5
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    Originally posted by kuphryn
    A string object does not have a NULL by default. In fact, a string object could contain more than just characters.

    Kuphryn
    I believe it does if you access it via c_str(), as in the example.
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  6. #6
    Registered User
    Join Date
    Nov 2001
    Posts
    1,348
    Okay. Good point.

    Kuphryn

  7. #7
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    John Bosko : post some more code to enable us to debug this one.
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Getting an error with OpenGL: collect2: ld returned 1 exit status
    By Lorgon Jortle in forum C++ Programming
    Replies: 6
    Last Post: 05-08-2009, 08:18 PM
  2. Compiling sample DarkGDK Program
    By Phyxashun in forum Game Programming
    Replies: 6
    Last Post: 01-27-2009, 03:07 AM
  3. Making C DLL using MSVC++ 2005
    By chico1st in forum C Programming
    Replies: 26
    Last Post: 05-28-2008, 01:17 PM
  4. Inheritance Hierarchy for a Package class
    By twickre in forum C++ Programming
    Replies: 7
    Last Post: 12-08-2007, 04:13 PM