今天在学习c++的过程中,遇到一个有趣的问题。当我使用VS2017写代码时,我发现即使我不引入cstring或者string.h,也可以使用strcat等函数,代码如下:
#include "pch.h"
#include <iostream>
//#include <cstring>
using namespace std;
int main()
{
const char* s1 = "Hello ";
const char* s2 = "123";
char a[20];
strcpy_s( a, s1 );
cout << strcat_s(a, 2 * strlen(s1) + 1, s1) << endl;
cout << ( strcmp( a, s1 ) == 0 ? "" : "not " ) << "equal\n";
cout << strcat_s( a, s2 ) << endl;
cout << a << endl;
cout << _strrev( a ) << endl;
cout << _strset_s( a, 'c' ) << endl;
cout << a << endl;
cout << ( strstr( s1, "ell" ) ? "" : "not " ) << "found\n";
cout << ( strchr( s1, 'c' ) ? "" : "not " ) << "found\n";
}
但是,如果用vscode,那么不引入cstring就会报错(显然,这是我们可以预期的“正常”的情况)。
那么,为什么呢?
初步判断是编译器问题。
因为之前在某本书中读到“BCB编译器为表示友好,默认包含了string资源”,所以推测VS2017所使用的的MSVC编译器也可能有类似的情况,这就导致了上述代码在VS上可以运行但是用vscode就不能运行(另一台电脑,用的是gcc编译器)的现象。
在这里顺便提一下,string和string.h以及cstring是不同的,具体的不同我就不说了,上网查一下就知道了。
主要是刚才举了个BCB和string的例子,防止某些萌新被我误导,把string和cstring弄混。
当然,具体原因我现在还不能确定,如果有知道的大佬,欢迎指正。
第一次写博客,如有不足之处希望大家体谅。