问题描述
有人可以解释为什么我在使用以下g ++编译器编译源代码时出现此错误
could someone explain why i am getting this error when i am compiling the source using following g++ compiler
#include <cstdio>
#include <string>
using namespace std;
int main()
{
char source_language[50];
scanf("%16s\n",source_language);
int length = sizeof(source_language);
int sizeofchar = strlen(source_language);
printf("%d\n",sizeofchar);
}
这给了我以下错误
test.cpp:在"int main()"函数中:
test.cpp: In function ‘int main()’:
test.cpp:31:错误:在此范围内未声明"strlen"
test.cpp:31: error: ‘strlen’ was not declared in this scope
当我将 #include< string>
更改为 #include< string.h>
或#include< cstring>
时,它工作正常,我需要找出使用#include< string>
和#include< string.h>
的区别.非常感谢您的帮助
when i change the #include <string>
into #include <string.h>
or #include<cstring>
, it works fine, i need to figure out what is the difference using #include<string>
and #include<string.h>
. really appreciate any help
推荐答案
C ++程序员通常必须处理至少两种类型的字符串:原始C样式字符串,通常声明为 char * str;
或 char str [123];
,可以使用 strlen()
等操作;和C ++样式的字符串,它们的类型为 std :: string
,并使用 string :: length()
之类的成员函数进行操作.不幸的是,这导致了一些混乱.
C++ programmers normally have to deal with at least 2 flavours of string: raw C-style strings, usually declared as char *str;
or char str[123];
, which can be manipulated with strlen()
etc.; and C++-style strings, which have the type std::string
and are manipulated with member functions like string::length()
. Unfortunately this leads to a bit of confusion.
- 在C语言中,
#include< string.h>
声明strlen()
等. - 在C ++中,您需要使用
#include< cstring>
,它在std
名称空间中声明它们,因此您可以将这些函数称为std:: strlen()
等,否则您需要使用命名空间std; 跟进,在这种情况下,您可以将它们称为
strlen()
像往常一样. C ++ 还具有一个完全独立的标头,称为
< string>
,该标头声明了C ++类型的std :: string
.此标头与strlen()
无关,因此包含该标头将不允许您访问strlen()
.
In C,
#include <string.h>
declaresstrlen()
et al.In C++, you need
#include <cstring>
instead, which declares them in thestd
namespace, so you can either call these functions asstd::strlen()
etc. or you need to follow up withusing namespace std;
, in which case you can then just call them asstrlen()
etc. as usual.C++ also has a totally separate header called
<string>
, which declares the C++ typestd::string
. This header has nothing to do withstrlen()
, so including it will not let you accessstrlen()
.
我不知道为什么梅赫达德·阿夫沙里(Mehrdad Afshari)删除了他的答案,而我在此重复一遍.
I don't know why Mehrdad Afshari deleted his answer, which I'm essentially repeating here.
这篇关于在g ++编译器中使用strlen获取数组的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!