2012-04-02 104 views
0

我想從vC++ 08中的目錄中檢索具有.jpg擴展名的文件。我對指針不太熟悉,所以在嘗試獲取字符串的長度時遇到錯誤碼。誰能幫我嗎??無法獲得vC++中的字符串長度

這裏是我的代碼..

#include<iostream> 
#include <string> 
#pragma warning(disable : 4996) 
#include "dirent.h" 
#pragma warning(default : 4996) 
using namespace std; 

int main(int argc, char *argv[]) 
{ 
if(argc != 2) 
{ 
    cout<<"Usage: "<<argv[0]<<" <Directory name>"<<endl; 
    return -1; 
} 

DIR *dir; 
dir = opendir (argv[1]); 
if (dir != NULL) 
{ 
    string name; string ext = ".jpg"; int len; 

    cout<<"Directory Listing for "<<argv[1]<<" : "<<endl; 
    struct dirent *ent; 
    while ((ent = readdir (dir)) != NULL) 
    { 
    name = ent->d_name; 
    len = name.length;     // here i got error... 
    name = name.substr(0, len-4); 

    if(_stricmp(name.c_str(), ext.c_str()) == 0) 
    { 
     cout<<ent->d_name<<endl; 
    } 
    else 
    { 
     cout<<"No JPG file"<<endl; 
    } 
    } 
} 
else 
{ 
    cout<<"Invalid Directory name"<<endl; 
    return -1; 
} 

return 0; 
} 

和錯誤是

example.cpp(29) : error C3867: 'std::basic_string<_Elem,_Traits,_Ax>::length': function call missing argument list; use '&std::basic_string<_Elem,_Traits,_Ax>::length' to create a pointer to member 
1>  with 
1>  [ 
1>   _Elem=char, 
1>   _Traits=std::char_traits<char>, 
1>   _Ax=std::allocator<char> 
1>  ] 
1>\example.cpp(29) : error C2440: '=' : cannot convert from 'unsigned int (__thiscall std::basic_string<_Elem,_Traits,_Ax>::*)(void) const' to 'int' 
1>  with 
1>  [ 
1>   _Elem=char, 
1>   _Traits=std::char_traits<char>, 
1>   _Ax=std::allocator<char> 
1>  ] 
1>  There is no context in which this conversion is possible 

在此先感謝...

回答

1
len = name.length(); 
      // ^^ 

length爲成員功能,而不是成員變量。你需要調用該函數。

+0

謝謝。這真是我的錯誤。這是你在深夜編碼時發生的情況。 – 2012-04-02 19:39:02