C ++
 Computer >> コンピューター >  >> プログラミング >> C ++

ASCIIファイル全体をC++std::stringに読み込みます


これは、ASCIIファイル全体をC++のstd::stringに読み込む簡単な方法です-

アルゴリズム

Begin
   Declare a file a.txt using file object f of ifstream type to perform read operation.
   Declare a variable str of string type.
   If(f)
      Declare another variable ss of ostringstream type.
      Call rdbuf() fuction to read data of file object.
      Put the data of file object in ss.
      Put the string of ss into the str string.
   Print the value of str.
End.

#include<iostream>
#include<fstream>
#include<sstream>
#include<string>
using namespace std;
int main() {
   ifstream f("a.txt"); //taking file as inputstream
   string str;
   if(f) {
      ostringstream ss;
      ss << f.rdbuf(); // reading data
      str = ss.str();
   }
   cout<<str;
}

入力

a.txt data file containing the text “hi”

出力

hi

  1. C ++でCSVファイルを読み取って解析する方法は?

    C ++でCSVファイルを解析するには、ライブラリを使用する必要があります。自分でファイルを読み取ると見逃す可能性がある場合が多いためです。 C ++用のBoostライブラリは、CSVファイルを読み取るための非常に優れたツールセットを提供します。たとえば、 例 #include<iostream> vector<string> parseCSVLine(string line){    using namespace boost;    std::vector<std::string> vec;   &n

  2. ファイルの内容を一度に文字列に読み込むC#プログラム

    ReadToEnd()メソッドを使用して、文字列内のファイルの内容を読み取ります。 StreamReaderの下に設定し、ファイルを読み取ります- using (StreamReader sr = new StreamReader("new.txt")){    string res = sr.ReadToEnd();    Console.WriteLine(res); } 以下は完全なコードです- 例 using System.IO; using System; public class Demo {   &nbs