計算を実行するために作成したコードを使用するには、外部テキスト ファイルからデータ (数値と文字列) を読み取り、それらを文字列または int/double のベクトルに格納する必要があります。これを行うためのテンプレート関数を作成しました。CashCow、Howard Hinnant、および wilhelmtell は、以前の問題を親切に解決してくれました。
この関数は ints/double では問題なく動作するようですが、文字列データに問題があります。
ベクトルに入るには外部ファイルの 1 行のデータが必要ですが、関数は複数行を読み取ります。これが私の言いたいことです。これが外部テキスト ファイル (以下) の内容であるとしましょう。
vectorOne // 1 つのベクトルのデータのサブセットの識別子
'1' '2' '3' // これらの値は 1 つのベクトル (vectorOne) に入る必要があります
vectorTwo // 別のベクトルのデータのサブセットの識別子 (vectorTwo)
'4' '5' '6' // これらの値は別のベクトルに入る必要があります
vectorThree // 別のベクター (vectorThree) のデータのサブセットの識別子
'7' '8' '9' // これらの値は別のベクトルに入る必要があります
データ サブセットの識別子/ラベル (vectorOne など) を探す場合、次の行のデータのみを結果ベクトルに入れる必要があります。問題は、識別子/ラベルの下のすべてのデータが結果ベクトルで終わることです。したがって、vectorTwo が必要な場合、結果のベクトルには "4, 5, 6" という要素が含まれているはずです。しかし、代わりに、4 から 9 が含まれています。私のコード (以下) では、次の行だと思いました。
while ( file.get() != '\n' );
読み取りが改行で停止することを保証します (つまり、データの各行の後)。
何がうまくいかないかについての提案に非常に感謝しています。
コードは次のとおりです(わかりやすくするために、文字列用に構成しました):
#include <algorithm>
#include <cctype>
#include <istream>
#include <fstream>
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <iterator>
using namespace std;
template<typename T>
void fileRead( std::vector<T>& results, const std::string& theFile, const std::string& findMe, T& temp )
{
std::ifstream file( theFile.c_str() );
std::string line;
while( std::getline( file, line ) )
{
if( line == findMe )
{
do{
std::getline( file, line, '\'' );
std::getline( file, line, '\'');
std::istringstream myStream( line );
myStream >> temp;
results.push_back( temp );
}
while ( file.get() != '\n' );
}
}
}
int main ()
{
const std::string theFile = "test.txt"; // Path to file
const std::string findMe = "labelInFile";
std::string temp;
std::vector<string> results;
fileRead<std::string>( results, theFile, findMe, temp );
cout << "Result: \n";
std::copy(results.begin(), results.end(), std::ostream_iterator<string>(std::cout, "\n"));
return 0;
}
ありがとう