C++ でファイル全体を std::string に読み込む最良の方法は何ですか? 同様の質問をしたいのですが、出力をテキスト ファイル内の行を含む配列/STL コンテナーにしたいという点が異なります。
C#/.net にはかなり便利なFile.ReadAllLines()ユーティリティ関数があります。適切な C++ (STL) バージョンはどのようなものでしょうか?
C++ でファイル全体を std::string に読み込む最良の方法は何ですか? 同様の質問をしたいのですが、出力をテキスト ファイル内の行を含む配列/STL コンテナーにしたいという点が異なります。
C#/.net にはかなり便利なFile.ReadAllLines()ユーティリティ関数があります。適切な C++ (STL) バージョンはどのようなものでしょうか?
C++ では、これを行うことができます。
構造体を次のように定義します。
struct line : std::string
{
friend std::istream & operator >> (std::istream & in, line & ln)
{
return std::getline(in, ln);
}
};
次にこれを行います:
std::ifstream file("file.txt");
std::istream_iterator<line> begin(file), end;
std::vector<std::string> allLines(begin, end);
終わり!
このアプローチでは、 iterator-pairbegin
とを直接操作できますend
。使用する必要はありませんstd::vector<std::string>
。line
に暗黙的に変換できることに注意してくださいstd::string
。したがって、標準アルゴリズムでbegin
とを使用できます。end
例えば、
最も長い直線を見つける:
auto cmp = [](line const &a, line const& b) { return a.size() < b.size(); };
std::string longestLine = *std::max_element(begin, end, cmp);
長さが より大きい行を数えます10
:
auto cmp = [](line const &a) { return a.size() > 10 ; };
size_t count = std::count_if(begin, end, cmp);
後で。begin
このようにして、とを直接操作できますend
。使用する必要はありませんstd::vector
。メモリを節約します。
それが役立つことを願っています。
標準イディオム:
#include <fstream>
#include <string>
#include <vector>
#include <utility>
std::ifstream infile("file.txt");
std::vector<std::string> v;
for (std::string line; std::getline(infile, line); )
{
v.push_back(std::move(line));
}
std::ifstream ifs(name);
std::vector<std::string> lines;
std::string line;
while (std::getline(ifs, line))
lines.push_back(line);
これは@Nawazのアイデアに対する私の試みです。std::string
少し気分が悪くなったので、からの継承は避けました。
#include <iostream>
#include <iterator>
#include <vector>
struct Line
{
operator const std::string&() const {return string;}
std::string string;
};
std::istream& operator>>(std::istream& in, Line& line)
{
return std::getline(in, line.string);
}
int main()
{
std::istream_iterator<Line> begin(std::cin), end;
std::vector<std::string> allLines(begin, end);
std::cout << allLines.size() << " lines read from file:" << std::endl;
std::copy(allLines.begin(), allLines.end(),
std::ostream_iterator<std::string>(std::cout, "|"));
return 0;
}