开发者

Reading a file to a string in C++

开发者 https://www.devze.com 2023-01-08 04:37 出处:网络
As somebo开发者_如何学运维dy who is new to C++ and coming from a python background, I am trying to translate the code below to C++

As somebo开发者_如何学运维dy who is new to C++ and coming from a python background, I am trying to translate the code below to C++

f = open('transit_test.py')
s = f.read()

What is the shortest C++ idiom to do something like this?


The C++ STL way to do this is this:

#include <string>
#include <iterator>
#include <fstream>

using namespace std;

wifstream f(L"transit_test.py");
wstring s(istreambuf_iterator<wchar_t>(f), (istreambuf_iterator<wchar_t>()) );


I'm pretty sure I've posted this before, but it's sufficiently short it's probably not worth finding the previous answer:

std::ifstream in("transit_test.py");
std::stringstream buffer;

buffer << in.rdbuf();

Now buffer.str() is an std::string holding the contents of transit_test.py.


You can do file read in C++ as like,

#include <iostream>
#include <fstream>
#include <string>

int main ()
{
    string line;
    ifstream in("transit_test.py"); //open file handler
    if(in.is_open()) //check if file open
    {
        while (!in.eof() ) //until the end of file
        {
            getline(in,line); //read each line
            // do something with the line
        }
        in.close(); //close file handler
    }
    else
    {
         cout << "Can not open file" << endl; 
    }
    return 0;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消