Search code examples
c++ifstreamgetline

read in txt file in C++


I have a .txt parameter file like this:

#Stage
filename = "a.txt";
...

#Stage
filename = "b.txt";
...

Basically I want to read one stage each time I access the parameter file. I planed to use getline in C++ with delimiter "#Stage" to do this. Or there is a better way to solve this? Any sample codes will be helpful.


Solution

  • Maybe I should express more clear. Anyway, I manage like this:

    ifstream file1;
    file1.open(parfile, ios::binary);
    if (!file1) {
        cout<<"Error opening file"<<parfile<<"for read"<<endl;
        exit(1);
    }
    
    std::istreambuf_iterator<char> eos;
    std::string s(std::istreambuf_iterator<char>(file1), eos);
    
    unsigned int block_begin = 0;
    unsigned int block_end = string::npos;
    
    for (unsigned int i=0; i<stage; i++) {
    
        if(s.find("#STAGE", block_begin)!=string::npos) {
        block_begin = s.find("#STAGE", block_begin);
        }
    }
    
    if(s.find("#STAGE", block_begin)!=string::npos) {
    block_end = s.find("#STAGE", block_begin);
    }
    
    
    string block = s.substr(block_begin, block_end);
    
    stringstream ss(block);
    ....