If I'm creating a new char[] to read in a text file:

char* pbuffer;
pbuffer = new char[length];

what is the maximum size length can be? Would a std::string be better? pbuffer will only be allocated one time in scope no matter what, and length is not known until run time depending on the size of the text file to be read.

Edited 6 Years Ago by Jsplinter: n/a

If you only want to allocate pbuffer once, then yes, I think a std::string probably would be a good choice. It's essentially a vector of char which gives you access to many of those features and functionalities. Plus, it gives you the option to use stringstreams and other more-convenient operators/methods for manipulation.

Comments
Absolutely!

It is fine to use a char* here over a std::string. You could determine the size of the file at runtime and allocate exactly that amount of memory for the buffer.

It is also more convenient to use a std::ifstream object over a std::stringstream/std::string to access the more-convenient operators/methods which Fbody mentioned.

>>what is the maximum size length can be?
The maximum value of unsigned int -- see your compiler's limits.h for that value.

If you are reading the text file one line at a time, such as using getline(), then use std::string instead of char* so that you don't have to guess (possibly wrong) about the length of a line.

Comments
thank you!

There are two main reasons people ever use "char*" in C++: either they haven't learned std::string yet (meaning they are within a few weeks of having started to learn C/C++); or they are writing code that interfaces to a C library or an API written in C. If that is not your case, use std::string, it will surely be more convenient and it is usually compatible with most C-string functions too, but with stringstreams and ifstream all functionalities you might desire are already available.

The saying goes that good C++ programmers actually program in "++C" because they make use of the added features over its predecessor (C), while poor C++ programmers think they are using an improvement over C but they are actually only getting the original value. So, please try and use the best tools for your job, and, unless there are special constraints, the C++ standard libraries usually has the better tools over C libraries.

Comments
good :)

Thank you. I reckon char[] can hold 2147483647 char, that's more than I would ever dream of using.

I will take the advice of those with more experience and use std::string, although it might not make a difference. Funny, Mike. I will try to use the pre-incremented ++C.

This question has already been answered. Start a new discussion instead.