LoginSignup
0
0

[C++ ] ifstreamとistringstream 違い

Last updated at Posted at 2024-04-05

主な違い

std::ifstreamとstd::istringstreamは、C++の標準ライブラリに含まれる入力ストリームのクラスであり、読み込みのソースが異なる点が主な違いです。

std::ifstream : ファイルからの入力

std::ifstreamは"Input File Stream"の略で、ファイルからの入力を扱います。
ディスク上のファイルを読み込むために使用されるクラスであり、ファイルからデータを読み取りたい場合に使います。

std::istringstream : 文字列からの入力

std::istringstreamは"Input String Stream"の略で、文字列からの入力を扱います。
メモリ上の文字列を入力ストリームとして扱い、そこからデータを読み取るために使用されるクラスです。文字列に格納されたデータを読み取りたい場合、または文字列を解析する際に使います。

<使用例>

  1. std::ifstream (ファイルからテキストを読み込む例)
#include <fstream>
#include <iostream>
#include <string>

int main() {
    std::ifstream file("example.txt");
    std::string line;
    while (std::getline(file, line)) {
        std::cout << line << std::endl;
    }
    return 0;
}

example.txtを作成した後に実行することを忘れないでください。

2 . std::istringstream (文字列からデータを解析する例)

#include <iostream>
#include <sstream>
#include <string>

int main() {
	std::string data = "100 neko";
	std::istringstream iss(data);
	int number;
	std::string animal;
	iss >> number >> animal;
	std::cout << number << " " << animal << std::endl;
	return 0;
}

このように、std::ifstreamはファイル入力に特化、std::istringstreamは文字列からのデータ読み込みに特化しています。
どちらもstd::istreamを基底クラスとしており、共通のインターフェイスを持っていますが、使用する場合に応じて選択します。

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0