Thread: sprintf with dynamic string

  1. #1
    Registered User
    Join Date
    Dec 2007
    Posts
    932

    sprintf with dynamic string

    I would need a dynamic pointer string at the end and i know that with sprinf and family i should use a char array.

    Its compiling and working this way but i prefer to ask you if its ok to do it like this because i know that with pointers we can have undefined behaviour.

    Code:
    int main ()
    {
        char * buffer = (char*) calloc (512, sizeof(char));
        char * str = "hello ";
        sprintf (buffer, "\n%s%s", str, "world\n");
        cout << buffer << endl;
        free(buffer);
        return 0;
    }
    Using Windows 10 with Code Blocks and MingW.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Why do you not use a std::string with its c_str() member function?
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Find out how to do the whole thing in C++.

    stringstream - C++ Reference
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  4. #4
    Registered User
    Join Date
    Aug 2010
    Location
    Poland
    Posts
    733
    Do you mean sprintf(s.c_str(), ...) ?!?!

  5. #5
    Registered User
    Join Date
    Dec 2007
    Posts
    932
    Yes that sounds more simple and i know how to do it with C++ strings but i think im still confused by
    all the people defending C and saying that C++ is bloated and C is lower level than C++.

    But just please tell me if its not true and i should choose C++.
    Using Windows 10 with Code Blocks and MingW.

  6. #6
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    If you're coding in C++, use C++'s features. Perhaps they are a little less efficient at a lower level, but the programming effort you save in the end is worth it. That's why people invented higher-level programming languages in the first place.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  7. #7
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    If you're going to use it, then use all of it properly.

    Casual mix and match will just lead to trouble.

    <yoda>
    C or C++, there is no C/C++
    </yoda>


    > Do you mean sprintf(s.c_str(), ...) ?!?!
    No, that will just blow up.
    The c_str() method returns a CONST pointer, and sprintf will try to modify it.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  8. #8
    Registered User
    Join Date
    Dec 2007
    Posts
    932
    Yes this one is not working.

    Code:
    sprintf(Str.c_str(), "%s####  %s  ####...", str2, List[0]);
    So a line like that in c++ would be much more lines.

    "but the programming effort you save in the end is worth it. That's why people invented higher-level programming languages in the first place."

    Yes that makes sense.

    Thanks to all of you.
    Using Windows 10 with Code Blocks and MingW.

  9. #9
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > So a line like that in c++ would be much more lines.
    Probably, but look at how easy they are to write one you understand how to do it.

    Now look at all the things that could go wrong with a terse C approach
    - not allocating any memory at all
    - not allocating enough of it
    - not freeing it when you're done
    - getting the format string wrong
    - not passing enough parameters
    All that book work, housekeeping and debugging time.

    Is it still worth the tradeoff?
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  10. #10
    Registered User
    Join Date
    Dec 2007
    Posts
    932
    You are 100% right and thanks for making that list.

    But my only problem is that im writing a GUI problem and win32 api functions use C strings.

    Now ive tried to rewrite the part of my program with c++ strings.

    I need to "walk" a pointer like: char * str++ in a loop and that i cant do with strings.
    So i used a vector like: myvector[0][vectorCounter++].

    But that i cant pass to a function that takes a LPCTSTR.
    Using Windows 10 with Code Blocks and MingW.

  11. #11
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    You can take a std::string and "convert" it to a char* very easily. That's what .c_str() is supposed to be for. I'm assuming LPCTSTR is really just a glorified char* so that should work for you.

    I need to "walk" a pointer like: char * str++ in a loop and that i cant do with strings.
    You can do that with iterators, which std::strings support. For example:
    Code:
    std::string name = "anonymous";
    for(std::string::iterator i = name.begin(); i != name.end(); ++ i) {
        char c = *i;
        std::cout << std::toupper(c);
    }
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  12. #12
    Registered User
    Join Date
    Dec 2007
    Posts
    932
    Awesome, thank you Dwks!
    Using Windows 10 with Code Blocks and MingW.

  13. #13
    Registered User
    Join Date
    Dec 2007
    Posts
    932
    Im sorry but this isnt working out.

    If i use c_str and i use a pointer on it, it will give me only one letter not the whole string.
    So its not like a char * str that i can inrement and i still always have the rest of the string.
    Cause thats what im looking for.

    And an iterator i cant pass as a char* in a function.

    So its not that simple as one would think.

    Code:
        string name = "anonymous";
        
        // this will give me only one letter
        cout <<  *name.c_str()+1;
    Last edited by Ducky; 09-17-2010 at 01:30 PM.
    Using Windows 10 with Code Blocks and MingW.

  14. #14
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    I don't know what you're trying to do. Maybe you should elaborate.

    c_str() gives you a pointer to the whole string. If you like you can assign it to another char* pointer and ++ that pointer to step through the string. And this char* can certainly be passed to a function expecting a C-style string.
    Code:
    for(char *p = str.c_str(); *p; p ++) {
        std::cout << *p;
    }
    
    std::printf("%s\n", str.c_str());
    Are you trying to create a string, or an array of strings?
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  15. #15
    Registered User
    Join Date
    Dec 2007
    Posts
    932
    Im using TextOut in a loop to create a ticker effect.

    Code:
    TextOut(hdc,88, 110, Str++, 23);
    My C string has to be global so it must be dynamic.

    Now if i have to reassign the c++ String to a C-string i came back where i started and
    i just might as well start out with a C string.

    Because the whole point of C++ strings was not to allocate and free memory.
    Last edited by Ducky; 09-17-2010 at 02:35 PM.
    Using Windows 10 with Code Blocks and MingW.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Polymorphism and generic lists
    By Shibby3 in forum C# Programming
    Replies: 9
    Last Post: 07-26-2010, 05:27 AM
  2. OOP Question DB Access Wrapper Classes
    By digioz in forum C# Programming
    Replies: 2
    Last Post: 09-07-2008, 04:30 PM
  3. Program using classes - keeps crashing
    By webren in forum C++ Programming
    Replies: 4
    Last Post: 09-16-2005, 03:58 PM
  4. Calculator + LinkedList
    By maro009 in forum C++ Programming
    Replies: 20
    Last Post: 05-17-2005, 12:56 PM
  5. Classes inheretance problem...
    By NANO in forum C++ Programming
    Replies: 12
    Last Post: 12-09-2002, 03:23 PM