Getting array length using strlen in g ++ compiler

can someone explain why I get this error when I compile the source using the 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); } 

it gives me the following error

test.cpp: In the function 'int main ():

test.cpp: 31: error: 'strlen was not declared in this area

when I change #include <string> to #include <string.h> or #include<cstring> it works fine, I need to find out what the difference is using #include<string> and #include<string.h> . really appreciate any help

+4
source share
4 answers

C ++ programmers usually have to deal with at least two line tastes: raw C-style strings, usually declared as char *str; or char str[123]; that can be controlled with strlen() , etc .; and C ++-style strings that are of type std::string and are managed using member functions such as string::length() . Unfortunately, this leads to some confusion.

  • In C, #include <string.h> declares strlen() , etc.
  • In C ++, you need #include <cstring> instead, declaring them in the std , so you can either call these functions like std::strlen() , etc., or you need to keep an eye on using namespace std; , and in this case, you can just call them as strlen() , etc., as usual.
  • C ++ also has a completely separate header named <string> , which declares a C ++ type std::string . This header has nothing to do with strlen() , so including it will not allow you to access strlen() .

I do not know why Mehrdad Afshari deleted his answer, which I, in essence, repeat here.

+7
source

You are trying to use the strlen function declared in string.h (or as a member of the std in cstring ). So, to use strlen , you must include one of these two headers.

The #include <string> option does not work simply because string - a completely unrelated C ++ - specific header file that has absolutely nothing to do with the string functions of the standard C library. What made you expect it to work?

+13
source
 #include<string> 

this is include for C ++ std :: string, not c string (link: http://www.cppreference.com/wiki/string/start )

and those:

 #include<cstring> 

and

 #include<string.h> 

for c lines (link: http://www.cplusplus.com/reference/clibrary/cstring/ )

+4
source

use string.length () instead of strlen ()

0
source

Source: https://habr.com/ru/post/1301205/


All Articles