简体   繁体   中英

how to take input a string of length 10^6 in c++?

we have to take input of a string such as : 1<=|S| <=10^6 (length of string) and perform some operation , let's leave operation , I want to only know how to take input of such a long string like 10^6 ? Can we take like this char S[1000001]; or which would be other better way? Kindly, help

Forget about using a c-style string and use a std::string instead. A std::string can hold std::string::max_size characters. On most implementations today that should be 4294967294 characters.

The benefit with use a std::string is that it automatically grows to accommodate the size you need. Since the memory is dynamically allocated you don't have to worry about running out of stack space as well. You could run out of memory on the heap as you would need about 4 GB of RAM to hold a max size string thought.

Can we take like this char S[1000001];

You can... but if S is an automatic variable, you'll spend most of your stack-space on that one array and you'll probably run out (depending on available stack space and how much the rest of your program needs).

Large arrays like these should be allocated dynamically. Unfortunately, it's not easy to say how big arrays/objects should be allocated dynamically. It depends on a few things such as:

  • Amount of total stack space which depends on the platform and may be configurable at run- or linktime.
  • Amount of stack space needed by the rest of your program. This depends on how deep nested function calls do you have and how much memory your functions need.

I use a few kilobytes as a rule of thumb to decide if I'll need dynamic memory. Or a few dozen bytes inside a recursive function that is expected to go deep.

or which would be other better way?

std::string allocates it's buffer dynamically, provides ways to manipulate the string, makes sure that you don't forget the zero terminator and takes care of mamory management (which would be an issue if you did dynamic allocation manually). I highly recommend you use it.

it depends if the string characters are unicode or not

you could use:

   char *txt = new char[1000000]  
   wchar_t *txt = new wchar_t[1000000];

also you can try using std::string or std::wstring like NathanOliver said

Use std::string .

Alternatively, if your data isn't being resized, you could opt to use a simple char array. Due to the size of the char array, I would suggest you allocate it with new and free it with delete . Otherwise, you may exhaust your stack size and cause a stack overflow.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM