+ Reply to Thread
Results 1 to 2 of 2

Thread: C++ string crashes while I assigned it in sprintf. Why?

  1. #1
    Junior Member
    Join Date
    Apr 2012
    Posts
    43

    C++ string crashes while I assigned it in sprintf. Why?

    Below code crashes:

    Code:
    void PrintOutput()
    {
    	std::string strMessage = "This statement is crashing! Why?" ;
    	char message[100] ;
    	sprintf(message, "%s.\n", strMessage) ;
    }
    What could be the reason?

    Please help.

  2. #2
    Junior Member
    Join Date
    Apr 2012
    Posts
    37
    Use below code fragment:

    Code:
    void PrintOutput()
    {
    	std::string strMessage = "This statement is crashing! Why?" ;
    	char message[100] ;
    	sprintf(message, "%s.\n", strMessage.c_str()) ;
    }
    You should use constant string returned by string class. So use string::c_str() method.

    Hope this helps.

+ Reply to Thread

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts