2010-02-13 99 views
4
使用的strlen數組的長度

有人能解釋爲什麼我收到的時候我使用下列G編譯源此錯誤++編譯器獲得的G ++編譯器

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

這給了我下面的錯誤

測試的.cpp:在函數 'INT主()':

TEST.CPP:31:錯誤: 'strlen的' 未在此範圍

當我改變宣佈#include <string>分成#include <string.h>#include<cstring>,它工作正常,我需要弄清楚使用#include<string>#include<string.h>有什麼區別。非常感謝所有幫助

+2

您可以編輯問題的清晰度? 「當我改變#include into #incude或#include」缺少一些信息時,我想。 –

+0

好的,完成了,thanx來展示它 – KItis

回答

7

C++程序員通常必須處理至少2種口味串的:原料C風格字符串,通常聲明爲char *str;char str[123];,其可以與strlen()等來操縱;和C++風格的字符串,其類型爲std::string,並使用成員函數string::length()進行操作。不幸的是,這導致了一些混亂。

  • 在C中,#include <string.h>聲明strlen() et al。
  • 在C++中,你需要#include <cstring>來代替,該聲明它們在std命名空間,這樣你就可以調用這些函數爲std::strlen()等,或者您需要using namespace std;跟進,在這種情況下,你就可以只調用它們的作爲strlen()等等。
  • C++ 有一個完全獨立的標頭,稱爲<string>,它聲明C++類型std::string。這個標題與strlen()無關,所以包括它在內不會讓你訪問strlen()

我不知道爲什麼Mehrdad Afshari刪除了他的答案,我在這裏基本上重複。

13

您正在嘗試使用strlen函數,該函數在string.h(或作爲cstring中的名稱空間std的成員)中聲明。因此,要使用strlen,您應該包含這兩個標題中的一個。它具有絕對沒有做與C標準庫字符串函數頭文件 -

因爲string是一個完全無關的C++的#include <string>變異並不是簡單的工作。是什麼讓你期望它會起作用?