无法在vc ++中获取字符串的长度

时间:2012-04-02 19:23:32

标签: string visual-c++ pointers string-length

我想从vc ++ 08中的目录中检索扩展名为.jpg的文件。我对指针不太熟悉,所以当我尝试在下面的代码中获取字符串长度时出错。谁能帮我吗??

这是我的代码..

#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 个答案:

答案 0 :(得分:1)

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

length是成员功能,而不是成员变量。你需要调用那个函数。