【问题标题】:Set string to file contents c++将字符串设置为文件内容c ++
【发布时间】:2015-03-28 03:08:55
【问题描述】:

我想知道是否有一种简单的方法可以将std::string 设置为C++ 中文件的内容。到目前为止,我在想这样的事情:(虽然我没有测试过,所以我不知道它是否有效)

#include <fstream>
#include <string>

int main(int argc, char *argv[]){

    fstream in("file.txt");
    string str;

    str = in;

    return 0;
}

这是实现此目的的方法吗?如果没有,有没有简单的方法可以做到这一点?谢谢!

【问题讨论】:

  • 为什么你还没有测试它?这是知道它是否有效的最简单方法:)
  • @Kelm:但不一定是最可靠的方法。 “看起来在工作”可能与“实际工作”有很大不同。尤其是在具有如此多未定义、未指定和实现定义行为的语言中。

标签: c++ string file-io


【解决方案1】:

这是使用vector&lt;string&gt; 的一种可能解决方案,每个元素都是一行。

#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main()
{
    // vector that will store all the file lines
    vector<string> textLines;  

    // string holding one line
    string line;  

    // attach input stream to file    
    ifstream inputFile("data.txt");

    // test stream status   
    if(!inputFile)
    {
        std::cerr << "Can't open input file!\n";
    }

    // read the text line by line
    while(getline(inputFile, line))
    {
        // store each line as vector element
        textLines.push_back(line);
    }

    // optional (stream object destroyed at end of function scope)
    inputFile.close();

    return 0;
}

【讨论】:

  • 谢谢你,这非常好。我将向量更改为只是一个字符串,然后不是 push_back,而是在其上附加了行。谢谢!
【解决方案2】:

有一个标准的方法:

std::ifstream     file("myfilename.txt");
std::stringstream buffer;
buffer << file.rdbuf();

std::string content( buffer.str() );

参考文献

【讨论】:

    【解决方案3】:

    试试这个

    #include <fstream>
    #include <cstdlib>
    std::string readText(const char* fileName)
    {
        std::ifstream file(fileName);
    
        if (!file.good())
        {
            std::cout << "file fail to load..." << fileName;
            exit(1);
        }
    
        return std::string(std::istreambuf_iterator<char>(file),        std::istreambuf_iterator<char>());
    
    }
    

    【讨论】:

      猜你喜欢
      • 2011-05-04
      • 2013-04-01
      • 1970-01-01
      • 2011-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-16
      • 1970-01-01
      相关资源
      最近更新 更多