How to read getline with a line feed ... but you have to add \n yourself.

 #include <iostream> #include <fstream> #include <string> void FuncReadFile(char* path, std::string &text) { //Переменная для чтения по указанному пути std::ifstream FileInput(path); std::string str; while (!FileInput.eof()) { getline(FileInput, str); text = text+ str + "\n"; } } int main() { setlocale(LC_ALL, "RUS"); std::string text; char* path = "input.txt"; FuncReadFile(path, text); std::cout << text<<std::endl; std::cout << "END" << std::endl; system("pause"); } 

    2 answers 2

     getline (FileInput,str,'\0'); 
    • one
      In fact, you read the entire file like this (if it does not contain binary zeros) into the str variable in a single getline() call. If there are zeros there, then you replace them with superfluous \n . And one of them (extra), you still add. - avp
    • @avp: there are no zeros in the text file (if it is utf-16, then you need to read it as a binary file if char used). - jfs
    • @jfs, but what does the file text have to do with it? - avp
    • @avp: you wrote: "If there are zeros there, then you replace them with superfluous \ n." . In the text file zeros - no problem. - jfs

    To read the entire file without conversions (such as the \r\n -> \n or conversions associated with the current locale), you can use the read() method:

     ifstream file(filename, ios::in | ios::binary | ios::ate); const ifstream::pos_type file_size = file.tellg(); vector<char> data(file_size); file.seekg(0, ios::beg); file.read(&data[0], file_size); // C++11 

    Result in vector data . Full code example . You can also use the string string data(file_size, '\0'); instead of a vector.

    Here is a comparison of the performance of several file reading methods in C ++ using different compilers for the platform: Reading .

    • Why do you have for file.read(&data[0], file_size); worth comment C++11 ? The vector has always been a continuous piece of memory. - Vladimir Gamalyan
    • @VladimirGamalian: things that are true for common implementations, and things guaranteed by the standard are different things in the general case. - jfs
    • std::vector is uninterrupted by the standard, you are probably confusing with std::string . - Vladimir Gamalyan
    • @VladimirGamalian: by what standard? Think what happens if the vector is empty. - jfs
    • file_size == 0 - jfs