次を含むiniファイル: address="localhost" username="root" password="yourpassword" database="yourdatabasename"
そして、ifstream で 2 つの "" の間の単語を見つけ、それを char に入れる必要があります。
これを行う方法はありますか??
各カップルの間に改行がある場合は、次のようにすることができます。
std::string line; //string holding the result
char charString[256]; // C-string
while(getline(fs,line)){ //while there are lines, loop, fs is your ifstream
for(int i =0; i< line.length(); i++) {
if(line[i] != '"') continue; //seach until the first " is found
int index = 0;
for(int j= i+1; line[j] != '"'; j++) {
charString[index++] = line[j];
}
charString[index] = '\0'; //c-string, must be null terminated
//do something with the result
std::cout << "Result : " << charString << std::endl;
break; // exit the for loop, next string
}
}
私は次のようにアプローチします。
std::istream& operator>>( std::istream &, NameValuePair & );
次に、次のようなことができます。
ifstream inifile( fileName );
NameValuePair myPair;
while( ifstream >> myPair )
{
myConfigMap.insert( myPair.asStdPair() );
}
ini ファイルにセクションが含まれており、それぞれに名前付き値のペアが含まれている場合、ロジックがストリームの失敗を使用せず、ステート マシンを備えたある種の抽象ファクトリを使用するように、セクションの最後まで読み取る必要があります。(あなたは何かを読んで、それが何であるかを判断し、あなたの状態を決定します).
名前と値のペアに読み込まれるストリームの実装に関しては、引用符をターミネータとして使用して、getline で実行できます。
std::istream& operator>>( std::istream& is, NameValuePair & nvPair )
{
std::string line;
if( std::getline( is, line, '\"' ) )
{
// we have token up to first quote. Strip off the = at the end plus any whitespace before it
std::string name = parseKey( line );
if( std::getline( is, line, '\"' ) ) // read to the next quote.
{
// no need to parse line it will already be value unless you allow escape sequences
nvPair.name = name;
nvPair.value = line;
}
}
return is;
}
トークンを完全に解析するまで、nvPair.name に書き込んでいないことに注意してください。ストリーミングが失敗した場合、部分的に書き込みたくありません。
いずれかの getline が失敗した場合、ストリームは失敗状態のままになります。これは、ファイルの終わりで自然に発生します。その理由で失敗した場合に例外をスローしたくありません。これは、ファイルの終わりを処理する間違った方法だからです。名前と値の間で失敗した場合、または名前の末尾に = 記号がない (ただし空ではない) 場合はスローできます。これは自然発生ではないためです。
これにより、引用符の間にスペースや改行さえも許可されることに注意してください。それらの間にあるものはすべて、別の引用以外に読み取られます。それらを許可する(そして値を解析する)には、エスケープシーケンスを使用する必要があります。
エスケープ シーケンスとして \" を使用した場合、値を取得するときに、値が \ で終わる場合は (および引用符に変更して) 「ループ」し、それらを連結する必要があります。