Home > Mobile >  C read specific range of line from file
C read specific range of line from file

Time:10-29

I have the following content in a file:

A(3#John Brook)
A(2#Allies Frank)
A(1#Lucas Feider)

I want to read the line piecemeal. First I want to read in order. For example, A than 3 than John Brook. Every thing is fine till 3 but how can I read John Brook without "#" and ")" as string.

I have a funciton and you can have a look my codes:

void readFile()
{

   ifstream read;
   char process;
   char index;
   string data;
   read.open("datas.txt");
   while(true)
   {
       read.get(process);
       read.get(index);
      
       // Here, I need to read "John Brook" for first line.
       //                      "Allies Frank" for second line.
       //                      "Lucas Feider" for third line.

   }
   read.close();
}

CodePudding user response:

First organize your data into some structure.

struct Data {
    char process;
    char index;
    std::string data;
};

Then implement function which is able to read single item. Read separators into temporary variables and then later check if they contain proper values. Here is an example assuming each item is in single line.

std::istream& operator>>(std::istream& in, Data& d) {
    std::string l;
    if (std::getline(in, l)) {
        std::istringstream in_line{l};
        char openParan;
        char separator;

        if (!std::getline(
                in_line >> d.process >> openParan >> d.index >> separator,
                d.data, ')') ||
            openParan != '(' || separator != '#') {
            in.setstate(std::ios::failbit);
        }
    }
    return in;
}

After that rest is quick and simple. https://godbolt.org/z/aGYvPeWfW

  •  Tags:  
  • c
  • Related