getting the length of an array using strlen in g++ compiler

淺唱寂寞╮ 提交于 2021-02-04 18:55:07

问题


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);
}

this gives me following error

test.cpp: In function ‘int main()’:

test.cpp:31: error: ‘strlen’ was not declared in this scope

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


回答1:


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.

  • In C, #include <string.h> declares strlen() et al.
  • In C++, you need #include <cstring> instead, which declares them in the std namespace, so you can either call these functions as std::strlen() etc. or you need to follow up with using namespace std;, in which case you can then just call them as strlen() etc. as usual.
  • C++ also has a totally separate header called <string>, which declares the C++ type std::string. This header has nothing to do with strlen(), so including it will not let you access strlen().

I don't know why Mehrdad Afshari deleted his answer, which I'm essentially repeating here.




回答2:


You are trying to use strlen function, which is declared in string.h (or, as a member of namespace std in cstring). So, in order to use strlen you should include one of those two headers.

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




回答3:


#include<string>

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

and those:

#include<cstring>

and

#include<string.h>

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




回答4:


use string.length() instead of strlen()



来源:https://stackoverflow.com/questions/2258561/getting-the-length-of-an-array-using-strlen-in-g-compiler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!