简体   繁体   English

在C ++中将文件读取到字符串

[英]Reading a file to a string in C++

As somebody who is new to C++ and coming from a python background, I am trying to translate the code below to C++ 作为一个刚接触C ++并来自python背景的人,我试图将下面的代码翻译成C ++

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

What is the shortest C++ idiom to do something like this? 做这样的事最短的C ++成语是什么?

The C++ STL way to do this is this: C ++ STL的方法是这样的:

#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 . 现在buffer.str()是一个std::string ,它transit_test.py的内容。

You can do file read in C++ as like, 您可以像在C ++中一样读取文件,

#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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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