ファイルから文字列または数値データを読み取り、データを文字列または int/double のベクトルに保存するためのテンプレート関数を作成しました。次に、データを使用して、作成した別のコードで計算を実行します。
これは単純な質問だと思うので、お詫び申し上げます...空白がある文字列データを読み取ることができません...たとえば、名と姓。「トム・スミス」が欲しいときは、「トム」しか出てこない)。グーグルによると、問題は >> であり、代わりに getline を使用する必要があるようです。>> を getline(test,100) に置き換えようとしましたが、「std::basic_istringstream の呼び出しに一致する関数がありません...」というエラーが発生します (エラー: 'std:: の呼び出しに一致する関数がありません)。 basic_ifstream >::getline(double&)')
誰かが私を正してくれたらとてもありがたいです!ストリームについて頭が回らないようです。
これはいくつかのサンプル データと私のコードです。ここで文字列用に構成しました。
labelInFile // 1 つのベクトルのデータのサブセットの識別子
'Tom Smith' 'Jackie Brown' 'John Doe' // これらの名前はベクトルの要素として終了する必要があります
#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& test )
{
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 >> test;
results.push_back( test );
}
while ( file.get() != '\n' );
}
}
}
int main ()
{
const std::string theFile = "test.txt"; // Path to file
const std::string findMe = "labelInFile";
std::string test;
std::vector<string> results;
fileRead<std::string>( results, theFile, findMe, test );
cout << "Result: \n";
std::copy(results.begin(), results.end(), std::ostream_iterator<string>(std::cout, "\n"));
return 0;
}