using fstream to read every character including spaces and newline

前端 未结 13 1564
一个人的身影
一个人的身影 2020-12-07 22:47

I wanted to use fstream to read a txt file.

I am using inFile >> characterToConvert, but the problem is that this omits any spaces an

13条回答
  •  半阙折子戏
    2020-12-07 23:14

    Probably the best way is to read the entire file's contents into a string, which can be done very easily using ifstream's rdbuf() method:

    std::ifstream in("myfile");
    
    std::stringstream buffer;
    buffer << in.rdbuf();
    
    std::string contents(buffer.str());
    

    You can then use regular string manipulation now that you've got everything from the file.

    While Tomek was asking about reading a text file, the same approach will work for reading binary data, though the std::ios::binary flag needs to be provided when creating the input file stream.

提交回复
热议问题