私はC ++に比較的慣れていないので、「ファイルから変数を作成する」方法を知りたいです。ファイルを読み取り、割り当て言語のようにシンボルをマーキングとして使用するプログラムを作成したいと考えています。
私はそれがこのような頻度を与えたいです:
!frequency:time,frequency:time;//!=start/;=end
これが私があなたの質問をどのように理解するかです。ファイルがありますtest.txt
:
time freq
0.001 12.3
0.002 12.5
0.003 12.7
0.004 13.4
次に、このファイルを読み込んで、さらに処理するためtime
に 1 つのコンテナと別のコンテナに格納します。freq
もしそうなら、あなたのプログラムは次のようになります:
#include<iostream>
using namespace std;
int main()
{
ifstream in_file("test.txt");
string label1, label2;
float val;
in_file >> label1; //"time"
in_file >> label2; // "freq"
vector<float> time;
vector<float> freq;
while (in_file >> val)
{
time.pushback(val);
in_file >> val;
freq.pushback(val);
}
}
私のコメントで言及したことに対するもう少し一般化された解決策:
#include <iostream>
#include <sstream>
int main()
{
std::map<std::string, std::vector<double> > values_from_file;
std::ifstream in_file("test.txt");
std::string firstLine;
std::getline(in_file, firstLine);
std::istringstream firstLineInput(firstLine);
// read all the labels (symbols)
do
{
std::string label;
firstLineInput >> label;
values_from_file[label] = std::vector<double>();
} while(firstLineInput);
// Read all the values column wise
typedef std::map<std::string, std::vector<double> >::iterator It;
while(in_file)
{
for(It it = std::begin(values_from_file);
it != std::end(values_from_file);
++it)
{
double val;
if(in_file >> val)
{
it->second.push_back(val);
}
}
}
}