首页 > 解决方案 > 如何在 C 中备份字符串

问题描述

如何以原始形式备份字符串?我正在使用 strncpy() 但是,当我尝试打印句子时,原始文本被改变了。这是一个例子:如果我输入“这是一个示例文本”来获取并要求打印句子,控制台会打印“TTTTs is a ample ttxt”。有人可以告诉如何使 sentenceBackup 变量具有备份并且句子正确显示为输入。

    //String variable to contain the user input.
    char sentence[] = "";
    char sentenceBackup[] ="";

    //this variable tracks the size of the user input.
    int sentenceLength;

    //ask the user forsinput
    printf("Enter a free formed sentence that needs to be sorted: \n");

    //accept the user entry into sentence.
    //scanf is deprecated since C11.
    gets(sentence);

    // keep a backup for further operation.
    strncpy(sentenceBackup, sentence, findLength(sentence));


    //display the sentence entered.
    printf("The sentence is : %s\n", sentence);

ps:如果我去掉strncpy()方法,源文本,即句子变量就可以正确显示了。

标签: cstringpointersc-stringsstrcpy

解决方案


  1. 的大小sentence不足以容纳输入。

  2. 其次,gets不推荐使用,所以不要使用它。从这个在线 C 参考

    gets() 函数不执行边界检查,因此该函数极易受到缓冲区溢出攻击。它不能安全使用(除非程序在限制标准输入上出现的内容的环境中运行)。出于这个原因,该功能已在 C99 标准的第三次勘误中被弃用,并在 C11 标准中完全删除。fgets() 和 gets_s() 是推荐的替代品。永远不要使用gets()。


推荐阅读