If I don't know the size a string will be, and if that size may change later, and if that string may contain '0' characters, what methods are there to do this? (I would prefer a professional/reliable method if possible)

Recommended Answers

All 4 Replies

std::string ?

If you don't want to use std::string for some reason, then you could use a std::vector< char >, or something like that. Or, you could make your own, simple struct for keeping a pointer to an array of char and a size:

struct StringWithNulls
    char* chars;
    unsigned size;

I would use std::string unless you have a really good reason though (as vmanes said).

You could declare a char[BUFSIZ]. It is a max length your system can use. Not exactly what you are describing, but it would get the job done.

You could declare a char[BUFSIZ]. It is a max length your system can use.

Um...no. BUFSIZ is a macro representing the size of the default buffer used by the stdio library. It's nearly always a great deal less than the maximum length string you could define. BUFSIZ also doesn't preclude you from using a longer string with the stdio library, it's only there to give the library something to work with when the programmer doesn't provide a buffer with setbuf(). And the buffer is only used for performance purposes within the library, functionality doesn't change even when stdio is unbuffered.

However, BUFSIZ is usually large enough to represent a reasonable default buffer size for the programmer. Common values are 512 and 1024, so if you want something "finite, but large enough" in less than robust programs, BUFSIZ is often an acceptable choice. I use it for test and example programs regularly. ;)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.