#include
using namespace std;
class STR {
private:
char* s; int m, n;
public:
STR(char* t) {
s = new char[strlen(t) + 1];
strcpy(s, t);
m = 0; n = 0;
}
void fun() {
char* p = s;
while (*p)
{
if (*p ==' ' || *p == ',' || *p == '.')m++;
if (*p == '.')n++;
p++;
}
}
void print() {
cout << "字符串:" << s << endl;
cout << "句子数:" << n << endl;
cout << "单词数:" << m << endl;
}
~STR() { delete[]s; }
};
void main()
{
char a[200] = "i am a student. i am twenty. i come from china.";
STR text(a);
text.fun();
text.print();
}
用的是vc++吧。vc++默认禁止你使用strcpy(也包括scanf gets等)
你有两个办法,一个参考:
https://blog.csdn.net/nannanzhang121/article/details/96830680
设置编译器,允许strcpy
另一个办法是使用
strcpy_s代替
strcpy_s(s,strlen(t) + 1,t);
在软件行业有一种提法叫“安全编码”,简而言之就是约束代码写法、库函数的用法等来尽可能降低程序出现安全涵洞的可能。
字串操作是常见的漏洞出处,strcpy是字串操作中常用的库函数,其原型为:
char *strcpy(char *dest, const char *src);
strcpy被称为“不安全”的函数,是因为当src的长度超过dest的有效长度时会发生内存溢出:
dest=new char[5]; src = "012"; //安全
dest=new char[5]; src = "0123"; //安全
dest=new char[5]; src = "0123456"; //不安全!发生内存溢出
因此,有些编译器开始提供更加安全的strcpy_s,其原型相较于strcpy会多出一个参数来传入dest的buffer长度:
errno_t strcpy_s(
char *dest,
rsize_t dest_size,
const char *src
);
这样,strcpy_s内部就可以识别出 src len > dest size 的情况,避免出现内存溢出了。
微软的编译器对strcpy报错,应该就是为了推动程序员改用strcpy_s而将strcpy逐步退出了,将来某个版本的VC就可能直接删除strcpy函数了。不过gcc/g++暂时还未支持strcpy_s。