对以点 (.) 结尾的行进行排序

Sort lines ending in dot (.)

本文关键字:排序 结尾      更新时间:2023-10-16

我的代码有点问题。我的代码应该去除除 .,: 和 ;然后在新行上对以点结尾的行进行排序。所以,像这样:

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

将变成:

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

现在,剥离非字母数字的代码的第一部分可以完美地工作。排序部分在一定程度上起作用。因此,在我的代码中,上面的行实际上变成了:

First, some characters, legal and illegal: 8skf.
This should be on a separate line. This too.
我知道这是因为这是一个新行

,我的代码在成为新行的过程中无法读取它。代码为:

   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;
}

我的代码首先通过调用函数来工作,该函数读取初始文件,去除非法字符,并写入临时文件。然后,它读取临时文件,查找点,并在截断后在初始文件中写入新行。提前谢谢。

通过擦除 for 循环内部分line字符串,循环索引将失效。ilength 都不再包含可以可靠地继续使用 for 循环的值。

不过,您实际上不需要从字符串中删除。您可以跟踪当前起始位置,并将其用作substr调用的第一个参数。