0

I'm relatively new to C++ and I want to ask how "make variables from a file". I want to write a program that reads the file and it uses symbols as markings, like an assigning language.

I want it to give out a frequency like this:

!frequency:time,frequency:time;//!=start/;=end
nikolas
  • 8,707
  • 9
  • 50
  • 70
lixpoxx
  • 9
  • 1

2 Answers2

1

Here is how I understand your question. You have a file test.txt:

time      freq
0.001     12.3
0.002     12.5 
0.003     12.7
0.004     13.4 

Then you want to read in this file, so that you have time in one container and freq in the other for further processing. If so then your program is like that:

#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);
    }   
 }
cpp
  • 3,743
  • 3
  • 24
  • 38
  • have you got a side where i can look after it? – lixpoxx Aug 21 '13 at 19:35
  • @lixpoxx: [here](http://www.cplusplus.com/doc/tutorial/files/) is a tutorial on C++ input/output with files if this is what you mean – cpp Aug 22 '13 at 10:49
0

A bit more generalized solution towards what I've mentioned in my comment:

#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);
            }   
        }
    }
}
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190