- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
C++ 中 strncpy
的等价物是什么? strncpy
在 C 中工作,但在 C++ 中失败。
这是我正在尝试的代码:
string str1 = "hello";
string str2;
strncpy (str2,str1,5);
最佳答案
相当于 C 的 strncpy()
(顺便说一句,在 C++ 中拼写为 std::strncpy()
,并且在标题中找到 <cstring>
)是 std::string
的赋值运算符:
std::string s1 = "Hello, world!";
std::string s2(s1); // copy-construction, equivalent to strcpy
std::string s3 = s1; // copy-construction, equivalent to strcpy, too
std::string s4(s1, 0, 5); // copy-construction, taking 5 chars from pos 0,
// equivalent to strncpy
std::string s5(s1.c_str(), std::min(5,s1.size()));
// copy-construction, equivalent to strncpy
s5 = s1; // assignment, equivalent to strcpy
s5.assign(s1, 5); // assignment, equivalent to strncpy
关于strncpy 的 C++ 等价物,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4681405/
我敢肯定以下这个问题已经被问了很多,但顺便问一下,因为我还没有找到答案。 我必须重新创建函数 strncpy(我不需要/不想要任何解决方案)并且我无法重现此函数的确切行为。 这是我的代码: int m
我对 strncpy 功能感到非常沮丧。我做了这样的事情: char *md5S; //which has been assign with values, its length is 44 char
我一直无法让这部分代码正常工作。我试图获取一个要复制的字符数组,这样我就可以计算出有多少 token 可以动态分配并保存它们以供检查环境变量。但是,当它尝试对原始字符串进行 strncpy 时,我一直
编辑:变量名 我正在制作一个链表,当我尝试释放一个节点时,它给了我一个错误。我跟踪我的代码,发现当我使用这段代码创建节点时,我的错误就根深蒂固了。 奇怪的是,如果我分配的字符比我想要的少一个,它就可以
当我在我的机器上运行一些代码时,它会按照我的预期运行。 当我在同事身上运行它时,它表现不佳。这就是发生的事情。 我有一个字符串,其值为: croc_data_0001.idx 当我对长度为 18 的字
基本上,我的程序使用链表向机器人发出命令。我正在使用 strcpy() 将命令复制到我的链表节点结构中,但它在末尾添加了不需要的字符(即“right”变成了“右\000-°\rd")。我使用过 str
我编写了一个程序来查找最长的单词并打印它。 我的代码是: #include #include #include int MaxWord(char text[],char[]); int main
如果我对字符串 cat 和 dog 使用 strncpy 函数。我不明白\0字符是否被计算在内,所以我想知道最终结果是否是catdo?还是类似于 cat\0do strncpy("猫", "狗", 2
我想做的是要求用户输入以下格式的内容:cd 目录。然后我将“cd”存储在一个字符串中,将“directory”存储在另一个字符串中。这是我的代码: void main() { char buf[
关闭。这个问题是opinion-based 。目前不接受答案。 想要改进这个问题吗?更新问题,以便 editing this post 可以用事实和引文来回答它。 . 已关闭 4 年前。 Improv
我正在为一个项目使用 C 样式字符串,但我自己有点困惑。我正在检查字符串以查看它们的前缀是什么(zone_、player_ 等),然后获取字符串的其余部分。 else if(strncmp(info,
我刚开始使用 C++,所以我可能在这里犯了一个愚蠢的错误。下面是我的代码以及注释中的输出。我正在使用 Xcode。 #include #include using namespace std;
我正在审查函数 strncpy 的字符串操作函数。我有 7 个输出而不是 3 个,谁能解释一下?非常感谢。 char x[] = "just see that."; char y[15
#include using namespace std #include int main(){ char token[] = "some random string"; cha
我最近遇到了一些遗留代码,并注意到有时(并非总是)以下代码片段需要很长时间才能执行。 #define NUM_OF_RECORDS 100000 char* pzBuffer = new char[N
我正在探索关于 strncpy 的 C,因为大多数人说它比 strcpy 更安全(附加参数,长度,以避免缓冲区溢出)。我还想找出非空终止字符串对程序的影响。这是我拥有的代码片段。 char passw
我想在 C 中模拟一个向下增长的调用堆栈并将以下内容压入堆栈: 这是我写的测试代码,我只尝试压入字符串,字对齐,然后将地址压入刚刚压入的字符串: #include #include #includ
我是 c 的新手,想将字符串分成两部分。这是我的代码: #include #include #include void test(char** a, char** b) { const ch
我需要通过添加“_out”和更改扩展名来修改通过参数传递的文件名。所以,首先,我复制没有扩展名的旧文件的名称,就像那样 char* arg1 = argv[1]; char* var1 = N
我正在逐行读取文件,其中每一行的格式为: “数字 1\t 数字 2”。 我正在使用 strtok 和 strncpy 拆分然后根据需要存储这两个值。但是,我发现在 strncpy 之后,number1
我是一名优秀的程序员,十分优秀!