【问题标题】:strncpy function not working for me correctlystrncpy 函数不适合我
【发布时间】:2014-03-24 01:49:30
【问题描述】:

我只是从 C++ 开始,所以在这里我可能会犯一个愚蠢的错误。下面是我的代码以及 cmets 中的输出。我正在使用 Xcode。

#include <iostream>
#include <string.h>

using namespace std;

 int main() {

          char myString[] = "Hello There";
          printf("%s\n", myString);

         strncpy(myString, "Over", 5); // I want this to print out "Over There"

         cout<< myString<<endl; // this prints out ONLY as "Over"

         for (int i = 0; i <11; i++){
         cout<< myString[i];
          }// I wanted to see what's going on this prints out as Over? There
          // the ? is upside down, it got added in

         cout<< endl;
         return 0;
}

【问题讨论】:

  • 简答:不要使用strncpy。它是一个只有一个真正目的的功能,所以它的真正用途是非常罕见的。它包含在标准库中几乎完全是历史的偶然。
  • 哈哈真有趣....这是我的测验和考试中使用的主要功能之一。
  • 听起来是时候解雇你的老师了。 :-)

标签: c++ strncpy


【解决方案1】:

问题

  • strncpy (destination, source, max_len)

strncpy 被定义为从sourcedestination 复制最多max_len 个字符,如果source 没有,包括尾随空字节在第一个 max_len 字节中包含一个空字节。

在您的情况下,尾随空字节将包括在内,并且 destination 将在 "Over" 之后直接以空结尾,这就是您看到所描述行为的原因。

在您致电strncpy 之后,myString 将因此比较等于:

"Over\0There"

解决方案

最直接的解决方案是不从"Over"复制尾随空字节,这就像指定4而不是5strncpy一样简单:

strncpy(myString, "Over", 4);

【讨论】:

  • 感谢您的解释。我现在明白了。我觉得这个字符串函数这样做很不幸。然而,Jerry 告诉我它很少使用,所以我认为那没关系(即使这是在我的课堂上经常使用的少数字符串函数之一)。
  • 恕我直言,更好的风格是 memcpy(myString, "Over", 4) ,因为 memcpystrncpy 更易于描述。
  • @MattMcNabb 我正在考虑将其包含在答案中,memcpy 的问题是如果size 恰好大于src 的实际长度,它将产生未定义的行为; strncpy 在这方面更安全。
  • 在那种情况下它不是未定义的(你的意思是如果size恰好大于src的长度)?无论哪种情况,我们都可能不应该使用幻数。
  • @MattMcNabb 是的,对不起.. 愚蠢的错字(我目前正在写另一个问题的答案),我修正了我的评论。不应该使用幻数,我同意你的观点。
【解决方案2】:

strncopy的文档如下:

char * strncpy ( char * destination, const char * source, size_t num );

将源的前 num 个字符复制到目标。如果结束 源 C 字符串(由空字符表示)的 在复制 num 个字符之前找到,填充目标 用零直到总共写入了 num 个字符。

通过调用strncpy(myString, "Over", 5),您实际上是在将“Over\n”复制到myString 中。您最好使用最后一个参数作为 strlen(source) 调用 strncpy。

【讨论】:

    【解决方案3】:

    试试下面的

    #include <iostream>
    #include <string.h>
    
    using namespace std;
    
     int main() {
    
       char myString[] = "Hello There";
       printf("%s\n", myString);
    
       strncpy(myString, "Over", 4); // I want this to print out "Over There"
       strcpy( myString + 4, myString + 5 ); 
    
       cout<< myString<<endl; // this prints out ONLY as "Over"
    
       for (int i = 0; i <10; i++){
        cout<< myString[i];
       }// I wanted to see what's going on this prints out as Over? There
        // the ? is upside down, it got added in
    
       cout<< endl;
    
       return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-17
      • 2017-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-22
      • 2011-08-11
      相关资源
      最近更新 更多