2012-04-02 106 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