[英]Need help using strncpy() in C++
I am stuck for hours during my assignment.我在任务期间被困了好几个小时。 Specifically, on this part:具体来说,在这部分:
The constructor should take a const-qualified C-Style string as its argument.构造函数应采用 const 限定的 C 样式字符串作为其参数。 Use the
strncpy()
function from the<cstring>
library to copy it into the underlying storage.使用<cstring>
库中的strncpy()
function 将其复制到底层存储中。 Be sure to manually null-terminate the attribute after you copy to assure that it is a valid C-String (in case the parameter contained a much larger string).请务必在复制后手动对属性进行空终止,以确保它是有效的 C 字符串(以防参数包含更大的字符串)。
Where am I making mistakes, and how should I change my code?我在哪里犯了错误,我应该如何更改我的代码?
#ifndef STRINGWRAPPER_H
#define STRINGWRAPPER_H
class StringWrapper{
public:
StringWrapper (const char myString);
const static int max_capacity = 262144;
private:
int size = 1;
char myString [40];
};
#endif
#include "StringWrapper.h"
#include <cstring>
StringWrapper::StringWrapper (const char myString){
strncpy(StringWrapper::myString, myString, sizeof(myString));
}
#include <iostream>
#include "ThinArrayWrapper.h"
#include "ArrayWrapper.h"
#include "StringWrapper.h"
#include <stdexcept>
int main(){
char myString[]{ "string" };
StringWrapper StringWrapper('h');
return 0;
}
First of all, your call to strncpy
is wrong.首先,您对strncpy
的调用是错误的。 Please check the reference regarding the strncpy
from here .请从此处查看有关strncpy
的参考。
According to the definition of strncpy
:根据strncpy
的定义:
char *strncpy(char *dest, const char *src, std::size_t count);
In your case, you are calling strncpy
like this:在您的情况下,您正在调用strncpy
,如下所示:
strncpy(StringWrapper::myString, myString, sizeof(myString));
Here, myString
is a const char
type variable.这里, myString
是一个const char
类型的变量。 You need to make it to const char *
.您需要使其成为const char *
。 If you like, you can check my modification of your code from here .如果你愿意,你可以从这里检查我对你的代码的修改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.