Maklaizer
Maklaizer

Reputation: 37

Read multiple variables from a text file in C++

I am assigning each variable for the moment using seperate text files. I have something in this form:

double ft_means[3];
double ft_std_dev[3];
inputFile.open("mean.txt");
if (!inputFile)
cout<< "Error";
count=0;
while(!inputFile.eof())
{
    inputFile >> ft_means[count];
    count++;
}

count= 0;
ifstream inputFile2;
inputFile2.open("std_dev.txt");
if (!inputFile2)
cout<< "Error";
count=0;
while(!inputFile2.eof())
{
    inputFile2 >> ft_std_dev[count];
    count++;
}
char line[20];
std::string words[405];
int i=0;
std::ifstream myfile ("features.txt");
if (myfile.is_open())
    {
        for(i=0; i<3; ++i) {
        myfile.getline(line, 3);
        words[i]=line;
        strcpy(line, "");
    }
    myfile.close();
}

My current text files are in the following form:

Mean.txt: 
11
23
36
std_dev.txt:
34
42
22
features.txt
abc[0]
abc[1]
abc[3]
abc[4]*abc[5]

My question is how can I assign the corresponding lines to each variable from the same text file. I want to no longer have seperate text files but only one text file that contains all the lines and then assign each variable to the corresponding lines of the text file. The new text file format can be for example in this form:

11
23
36

34
42
22

abc[0]
abc[1]
abc[3]
abc[4]*abc[5]

Upvotes: 0

Views: 441

Answers (1)

Botje
Botje

Reputation: 30807

Assuming you have different blocks in your file, you can use the following structure:

std::string line;

// output variables
std::vector<double> means;
std::vector<double> stddevs;
std::vector<std::string> expressions;

// part one: means
while (std::getline(inputFile, line) && !line.empty()) {
    double mean;
    std::istringstream(line) >> mean;
    means.push_back(mean);
}

// part two: stddevs
while (std::getline(inputFile, line) && !line.empty()) {
    double stddev;
    std::istringstream(line) >> stddev;
    stddevs.push_back(stddev);
}

// part three: expressions
while (std::getline(inputFile, line) && !line.empty()) {
    expressions.push_back(line);
}

The condition in each while loop checks that you have not reached the end of the file and that you have not just read an empty line. The std::istringstream object turns a string into a stream so you can use the regular extraction operator on it.

You can add some using statements to bring the various classes in scope so you can get rid of some of the std:: noise, but that is up to you.

Upvotes: 1

Related Questions