在g ++编译器中使用strlen获取数组的长度 [英] getting the length of an array using strlen in g++ compiler

查看:68
本文介绍了在g ++编译器中使用strlen获取数组的长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释为什么我在使用以下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> 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().

我不知道为什么梅赫达德·阿夫沙里(Mehrdad Afshari)删除了他的答案,而我在此重复一遍.

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

这篇关于在g ++编译器中使用strlen获取数组的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆