Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 930
KItis Avatar asked Nov 29 '22 11:11

KItis


1 Answers

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?

like image 177
AnT Avatar answered Dec 06 '22 21:12

AnT