简体   繁体   中英

Sort lines ending in dot (.)

I have a bit of an issue with my code. My code should be stripping all non-alphanumeric characters except .,: and ; and then sorting lines ending in dots on new lines. So, something like:

First, some characters, legal and illegal: )(=8skf-=&. This should be on a separate line. This too.

would become:

First, some characters, legal and illegal: 8skf.
This should be on a separate line.
This too.

Now, the first part of the code, which strips non-alphanumerics works perfectly. The sorting part works up to a point. So, in my code, the above line actually becomes:

First, some characters, legal and illegal: 8skf.
This should be on a separate line. This too.

I understand that this is because this is a new line and my code cannot read it in the process of becoming a new line. The code is:

   int writeFinalv(string path) {
   readTempFiles(path.c_str());
   string line;
   string nline;
   int start;
   int lnth;
   ifstream temp("temp.txt");
   ofstream final;
   int length;
   final.open(path.c_str(), ios::out | ios::trunc);
   if(temp.is_open()) {
        while(getline(temp, line)) {
            length = line.length();
            for(int i = 0; i < length; i++) {
                if(line[i] == '.') {
                    if(line[i+1] == ' ') {
                        nline = line.substr(0, (i+2));
                    }
                    else {
                        nline = line.substr(0, (i+1));
                    }
                    final << nline << "\n";
                    start = line.find(nline);
                    lnth = nline.length();
                    line.erase(start, lnth);
                }
              }
           }
        }
   else {
      error = true;
   }
   return 0;
}

My code first works by calling the function which reads the initial file, strips it of illegal characters, and writes to a temporary file. Then, it reads the temporary file, finding dots, and writing the new lines in the initial file, after truncating it. Thanks in advance.

By erasing part of the line string inside the for loop, the loop indexing is invalidated. Both i and length no longer hold values that you can reliably keep using to continue the for loop.

You don't actually need to erase from the string though. You can keep track of the current start position, and use that as the first parameter to the substr calls.

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