std::basic_istream
から特定の文字数を抽出してstd::string
に保存すると、安全で安全な方法はありますか?特定の文字数をstd :: basic_istreamからstd :: stringにコピーする
result
を取得するために
char[]
を使用しますが、私はPODの種類を回避し、より安全でより保守何か確保したいと考え、以下のプログラムで
:
#include <sstream>
#include <string>
#include <iostream>
#include <exception>
int main()
{
std::stringstream inss{std::string{R"(some/path/to/a/file/is/stored/in/50/chars Other data starts here.)"}};
char arr[50]{};
if (!inss.read(arr,50))
throw std::runtime_error("Could not read enough characters.\n");
//std::string result{arr}; // Will probably copy past the end of arr
std::string result{arr,arr+50};
std::cout << "Path is: " << result << '\n';
std::cout << "stringstream still has: " << inss.str() << '\n';
return 0;
}
代替:
- 変換を上の文字列全体にストリーム:
std::string{inss.c_str()}
- これは悲しいldはストリーム全体のコピーを作成します。
- は、これはまだ中間PODの配列を使用することになり
char[]
- を受け入れるようにテンプレート関数を記述します。ループ内
- 使用
std::basic_istream::get
一緒std::basic_string::push_back
- でループを文字の必要数を読み取るために少し扱いにくいようだが、それは、配列を避けるん。
可能な複製(C++ 11以降):[?コピーせずにstringstreamのうち、文字を取得する方法](http://stackoverflow.com/questions/28663075/how-to-get-characters-out -of-stringstream-without-copy) – NathanOliver
ファイル名を50文字以下にすることは保証されていますか? –
@QPaysTaxesファイル形式には、ファイル名に割り当てられた最初の50文字が含まれています。したがって、ファイル形式が同じである限り保証されます。ファイル形式が変更され、コードが変更される危険性があります。 – wally