【问题标题】:Sort lines ending in dot (.)对以点 (.) 结尾的行进行排序
【发布时间】:2016-07-12 09:43:29
【问题描述】:

我的代码有点问题。我的代码应该剥离除 .,: 和 ; 之外的所有非字母数字字符然后在新行上对以点结尾的行进行排序。所以,类似:

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

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

【问题讨论】:

  • 您的具体问题是什么?

标签: c++ string file


【解决方案1】:

通过擦除 for 循环内的 line 字符串的一部分,循环索引无效。 ilength 不再保存您可以可靠地继续使用以继续 for 循环的值。

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

【讨论】:

  • 那么,基本上将擦除部分移出循环或跟踪开始位置?
  • @CrAzYPiLoT :摆脱erase 调用,并跟踪当前行的开头。
  • 现在有点用了。现在我得到了:First, some characters, legal and illegal: 8skf. First, some characters, legal and illegal: 8skf. This should be on a separate line. First, some characters, legal and illegal: 8skf. This should be on a separate line. This too. 我之前得到了这个结果,当所有代码都没有擦除调用时。
  • @CrAzYPiLoT :好吧,您必须不断更新起始值以指向当前句子的开头。
  • 现在效果更好了。不过,一个问题,现在我得到了:First, some characters, legal and illegal: 8skf. This should be on a separate line. This too.This too.“这也是。”第二行是问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-27
相关资源
最近更新 更多