首页 > 解决方案 > 如何使此功能停止在 N 个字符/

问题描述

所以我有这个任务是获取一个文本文件的内容并将其复制到另一个。我们必须重写 strncpy 默认函数,但略有不同。以下是实验室明确写下的内容:

此函数替换 std::strncpy 函数。也就是说,它将 s2 的内容复制到 s1,但不超过 N 个字符。提示:由于 strlength(和 std::strlen)不计算空终止字符,请记住在调用 strncopy(和 std::strncpy)时将该数字加一。为避免产生分段冲突,您必须在取消引用 s2 以将数据复制到 s1 之前检查是否遇到了空终止字符。同样,将您的代码基于指针循环。

这是我到目前为止的功能:

void strncopy(char *s1, const char *s2, int N){

    // return if no memory is allocated to the s1
    if (s1 == NULL)
       NULL;

    // take a pointer pointing to the beginning of s1 string
    char *ptr = s1;

    // copy the C-string pointed by s2 into the array
    // pointed by s1
    while (*s2 != '\0'){

        if (*s1 == N){
            break;
        } 

     //   *s1 = *s2;
        s1++;
        s2++;

    }

    // include the terminating null character
    *s1 = '\0';
}

它似乎存在的问题是循环在达到 N 个字符时没有停止。

这是我实现此功能的主要功能的一部分:

int main(int argc, char *argv[]) {


  // check for four command line arguments
  // if not, print error message and bail out
    if (argc != 4){
        cerr<<"Error";
        return -1;;
    }

 // declare two streams: file1, file2
   fstream file1;
   fstream file2;

 // declare two char text line arrays
    char textline1[256];
    char textline2[256];

  if (strcompare(argv[1], "-copy") == 0) {
    //open file1 for reading
      file1.open(argv[2]);
      //open file2 for writing
      file2.open(argv[3]);

            //read text line 1 frome file1
      while (file1.getline(textline1, 256)) {
      // determine length of textline1
      char t1 = strlength(textline1);
     // copy textline1 to textline2
        strncopy(textline2, textline1, (t1+1));
     // write textline2 + newline to file2
        file2 << textline2 << '\n';
    }
  }

这是我要复制的文件中的文本:

船长日志,星历 3192.1。进取号正在前往星团 NGC 321 的途中。目标是与已知存在的文明建立外交关系。我们已向星团的主行星 Eminiar 7 发送了一条消息,告知他们我们的友好意图。我们正在等待答案。

这就是我实际复制的内容:

船长日志,星历 3192.1。进取号正在前往星团 NGC 321 的途中。目标是与已知存在的文明建立外交关系。我们已向星团的主行星 Eminiar 7 发送了一条消息,告知他们我们的友好意图。我们正在等待答案。n answer.cluster, .

有谁知道我的问题是什么?很抱歉,这是一个愚蠢的问题,但是自从课程只在线上进行以来,很难从讲师和助教那里获得帮助。

标签: c++loops

解决方案


目前你有以下检查长度:

if (*s1 == N){
    break;
} 

但是,由于s1其中不包含长度(大概),因此您正在比较 中的字符s1N这可能是错误的(但如果s1未初始化,则为 UB)。

您可以像这样修改您的while条件:

while (*s2 != '\0' && N--)

N达到 0 时,它的条件为假,因此停止循环。这假设N一开始就大于或等于零。

另外,要添加,您有

// return if no memory is allocated to the s1
if (s1 == NULL)
    NULL;

这不会返回,它实际上什么都不做。您想要执行以下操作:

if ( s1 == NULL )
    return;

PS:如果您使用的是 C++11 或更高版本,您可能需要考虑使用nullptr而不是。NULL


推荐阅读