c - 如何在 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()方法,源文本,即句子变量就可以正确显示了。
解决方案
的大小
sentence
不足以容纳输入。其次,
gets
不推荐使用,所以不要使用它。从这个在线 C 参考:gets() 函数不执行边界检查,因此该函数极易受到缓冲区溢出攻击。它不能安全使用(除非程序在限制标准输入上出现的内容的环境中运行)。出于这个原因,该功能已在 C99 标准的第三次勘误中被弃用,并在 C11 标准中完全删除。fgets() 和 gets_s() 是推荐的替代品。永远不要使用gets()。
推荐阅读
- firebase - 使用 Cloud Functions 在 Firestore 上创建用户时发送电子邮件
- javascript - 以下如何在 Javascript 中逐步执行?
- python-3.x - Python tkinter 网格,在 ScrolledText 小部件中忽略行值
- javascript - 如何从 GET 请求中将数据分配给变量
- android - 如何将推送通知用于受信任的 Web 活动
- python - python将数据放入firebase实时数据库,但角度从云firestore抓取数据
- laravel - laravel:搜索表单,其中 '<='
- r - 试图理解生成泊松随机变量的逆变换方法
- typescript - 将数字转换为字符串而不扩展类型
- google-chrome - SSL 站点错误 ERR_BAD_SSL_CLIENT_AUTH_CERT - MAC OSX - 仅限 Chrome