how to pre-allocate memory for a std::string object?

后端 未结 7 1985
刺人心
刺人心 2020-11-27 18:38

I need to copy a file into a string. I need someway to preallocate memory for that string object and a way to directly read the file content into that string\'s memory?

7条回答
  •  醉话见心
    2020-11-27 18:52

    This should be all you need:

    ostringstream os;
    ifstream file("name.txt");
    os << file.rdbuf();
    
    string s = os.str();
    

    This reads characters from file and inserts them into the stringstream. Afterwards it gets the string created behind the scenes. Notice that i fell into the following trap: Using the extraction operator will skip initial whitespace. You have to use the insertion operator like above, or use the noskipws manipulator:

    // Beware, skips initial whitespace!
    file >> os.rdbuf();
    
    // This does not skip it
    file >> noskipws >> os.rdbuf(); 
    

    These functions are described as reading the stream character by character though (not sure what optimizations are possible here, though), i haven't timed these to determine their speed.

提交回复
热议问题