如何使用strncpy_s解决此问题 [英] How do I solve this issue with strncpy_s
问题描述
当我使用strncpy时出现错误:
错误C4996' strncpy ':此函数或变量可能不安全。请考虑使用strncpy_s代替。禁用弃用,请使用_CRT_SECURE_NO_WARNINGS。
当我尝试' strncpy_s '时出现错误:
错误(活动)E0304没有重载函数实例strncpy_s匹配参数列表
我尝试过:
When I use "strncpy" I had the error:
"Error C4996 'strncpy': This function or variable may be unsafe. Consider using strncpy_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS."
and when I try 'strncpy_s' I had the error:
"Error (active) E0304 no instance of overloaded function "strncpy_s" matches the argument list"
What I have tried:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <crtdbg.h> // For _CrtSetReportMode
#include <errno.h>
bool GetWord(char* theString,
char* word, int& wordOffset);
// driver program
int main()
{
const int bufferSize = 255;
char buffer[bufferSize + 1]; // hold the entire string
char word[bufferSize + 1]; // hold the word
int wordOffset = 0; // start at the beginning
std::cout << "Enter a string : ";
std::cin.getline(buffer, bufferSize);
while (GetWord(buffer, word, wordOffset))
{
std::cout << "Got this word: " << word << std::endl;
}
return 0;
}
// function to parse words from a string.
bool GetWord(char* theString, char* word, int& wordOffset)
{
if (theString[wordOffset] == 0) // end of string?
return false;
char *p1, *p2;
p1 = p2 = theString + wordOffset; // point to the next word
// eat leading spaces
for (int i = 0; i<(int)strlen(p1) && !isalnum(p1[0]); i++)
p1++;
// see if you have a word
if (!isalnum(p1[0]))
return false;
// p1 now points to start of next word
// point p2 there as well
p2 = p1;
// march p2 to end of word
while (isalnum(p2[0]))
p2++;
// p2 is now at end of word
// p1 is at beginning of word
// length of word is the difference
int len = int(p2 - p1);
// copy the word into the buffer
strncpy(word, p1, len);
// null terminate it
word[len] = '\0';
// now find the beginning of the next word
for (int j = int(p2 - theString); j<(int)strlen(theString)
&& !isalnum(p2[0]); j++)
{
p2++;
}
wordOffset = int(p2 - theString);
return true;
}
推荐答案
有两种可能的解决方案:
1.将_CRT_SECURE_NO_WARNINGS添加到项目中设置和使用strncpy();
2.使用
The are 2 possible solutions:
1. Add _CRT_SECURE_NO_WARNINGS to your project's settings and use strncpy();
2. Use
strncpy_s(word, p1, len);
strncpy [ ^ ]和 strncpy_s [ ^ ]有不同的签名,即strncpy_s
需要目标字符串的大小作为附加参数。因此你必须这样称呼
strncpy[^] and strncpy_s[^] have different signatures, namelystrncpy_s
needs the size of the destination string as additional parameter. Hence you would have to call it this way
strncpy(word, word_size, p1, len);
(并且您必须相应地更改 GetWord
签名,以便传递 word_size
)。
另一种选择是忽略或取消警告。
(and you would have to change GetWord
signature accordingly, in order to pass word_size
).
Another option is ignoring or suppressing the warning.
您是否检查了文档 strncpy_s,_strncpy_s_l,wcsncpy_s,_wcsncpy_s_l,_mbsncpy_s,_ _ _ _ _ _ _ _ _ @ target =_ blanktitle =New Window> ^ ]?
这篇关于如何使用strncpy_s解决此问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!