简体   繁体   中英

C++: Read uncertain number of variables in a text file and modify in struct, then replace the line in the text file

Our instructor asks us to read a text file and store them into different struct and array, then allow the user to modify. But when I used fstream >> name >> day >>...>> roster and get the text line by line. It always errors, maybe because the size of each line is different.

Class header

Class Course
private: 
   string name;
   int num_of_student;
   string *roster;

Struct class_time
   string day;
   string time;

test.txt(the first line can be ignored)

<name><day><time><num_of_student><roster(student ids separate by space)>
CS T 2pm 3 01 02 03
Math TH 10am 2 03 04

I have no idea how to read this type of text file and store them into different array or local variables.

Update: That is what I did after and successfully get each variable in the file.

num_courses(int){
// function get num of lines in text file
}

void load_Data(){
fstream read;
string name1, day1, time1;
int enroll;
int num_c; // number of courses
read.open("test.txt",ios::in);
if(!read.is_open()){
    cout << "No file exist." << endl;
}
num_courses(num_c);
Course course[num_c];
class_time sch[num_c];
while(!read.eof()) {
    for (int i = 0; i < num_c; i++) {
        read >> name1 >> day1 >> time1 >> enroll;
        course[i].name = name1;
        sch[i].day = day1;
        sch[i].time = time1;
        course[i].num_of_student = enroll;
        string ros[enroll];
        for (int j = 0; j < enroll; j++) {
            read >> ros[j];
            course[i].roster[j] = ros[j];
        }
    }
}

and Now I want to replace a certain line in the test.txt after modifying those variables, should I use ofstream and delete everything in the file, and replace by the updated course info. Or there is an easy way can replace a certain line in text file?

Seems like you want to read csv data. However, you need to ignore the title line-

I would recommend to use a "modern" C++ approach.

And still all people talking about csv are linking to How can I read and parse CSV files in C++? , the questions is from 2009 and now over 10 years old. Most answers are also old and very complicated. So, maybe its time for a change.

In modern C++ you have algorithms that iterate over ranges. You will often see something like "someAlgoritm(container.begin(), container.end(), someLambda)". The idea is that we iterate over some similar elements.

In your case we iterate over tokens in your input string, and create substrings. This is called tokenizing.

And for exactly that purpose, we have the std::sregex_token_iterator . And because we have something that has been defined for such purpose, we should use it.

This thing is an iterator. For iterating over a string, hence sregex. The begin part defines, on what range of input we shall operate, then there is a std::regex for what should be matched / or what should not be matched in the input string. The type of matching strategy is given with last parameter.

  • 1 --> give me the stuff that I defined in the regex and
  • -1 --> give me that what is NOT matched based on the regex.

So, now that we understand the iterator, we can std::copy the tokens from the iterator to our target, a std::vector of std::string . And since we do not know, how may columns we have, we will use the std::back_inserter as a target. This will add all tokens that we get from the std::sregex_token_iterator and append it ot our std::vector<std::string>> . It does'nt matter how many columns we have.

Good. Such a statement could look like

std::copy(                          // We want to copy something
    std::sregex_token_iterator      // The iterator begin, the sregex_token_iterator. Give back first token
    (
        line.begin(),               // Evaluate the input string from the beginning
        line.end(),                 // to the end
        re,                         // Add match a comma
        -1                          // But give me back not the comma but everything else 
    ),
    std::sregex_token_iterator(),   // iterator end for sregex_token_iterator, last token + 1
    std::back_inserter(cp.columns)  // Append everything to the target container
);

Now we can understand, how this copy operation works.

Next step. We want to read from a file. The file conatins also some kind of same data. The same data are rows.

And as for above, we can iterate of similar data. If it is the file input or whatever. For this purpose C++ has the std::istream_iterator . This is a template and as a template parameter it gets the type of data that it should read and, as a constructor parameter it gets a reference to an input stream. It doesnt't matter, if the input stream is a std::cin , or a std::ifstream or a std::istringstream . The behaviour is identical for all kinds of streams.

And since we do not have files an SO, I use (in the below example) a std::istringstream to store the input csv file. But of course you can open a file, by defining a std::ifstream testCsv(filename) . No problem.

And with std::istream_iterator , we iterate over the input and read similar data. In our case one problem is that we want to iterate over special data and not over some build in data type.

To solve this, we define a Proxy class, which does the internal work for us (we do not want to know how, that should be encapsulated in the proxy). In the proxy we overwrite the type cast operator, to get the result to our expected type for the std::istream_iterator .

And the last important step. A std::vector has a range constructor. It has also a lot of other constructors that we can use in the definition of a variable of type std::vector . But for our purposes this constructor fits best.

So we define a variable csv and use its range constructor and give it a begin of a range and an end of a range. And, in our specific example, we use the begin and end iterator of std::istream_iterator .

If we combine all the above, reading the complete CSV file is a one-liner , it is the definition of a variable with calling its constructor.

Please see the resulting code:

#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <vector>
#include <iterator>
#include <regex>
#include <algorithm>

std::istringstream testCsv{ R"(CS T 2pm 3 01 02 03
Math TH 10am 2 03 04
)" };


// Define Alias for Easier Reading
using Columns = std::vector<std::string>;
using CSV = std::vector<Columns>;


// Proxy for the input Iterator
struct ColumnProxy {    
    // Overload extractor. Read a complete line
    friend std::istream& operator>>(std::istream& is, ColumnProxy& cp) {

        // Read a line
        std::string line; cp.columns.clear();
        std::getline(is, line);

        // The delimiter
        const std::regex re(" ");

        // Split values and copy into resulting vector
        std::copy(std::sregex_token_iterator(line.begin(), line.end(), re, -1),
            std::sregex_token_iterator(),
            std::back_inserter(cp.columns));
        return is;
    }

    // Type cast operator overload.  Cast the type 'Columns' to std::vector<std::string>
    operator std::vector<std::string>() const { return columns; }
protected:
    // Temporary to hold the read vector
    Columns columns{};
};


int main()
{
    // Define variable CSV with its range constructor. Read complete CSV in this statement, So, one liner
    CSV csv{ std::istream_iterator<ColumnProxy>(testCsv), std::istream_iterator<ColumnProxy>() };

    // Print result. Go through all lines and then copy line elements to std::cout
    std::for_each(csv.begin(), csv.end(), [](Columns& c) {
        std::copy(c.begin(), c.end(), std::ostream_iterator<std::string>(std::cout, " ")); std::cout << "\n";   });
}

I hope the explanation was detailed enough to give you an idea, what you can do with modern C++.

This example does basically not care how many rows and columns are in. It will eat everything.

Please do not forget do read the first line in your real file with std::getline and throw it away.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM