开发者

Compare characters at the end of the string C++

开发者 https://www.devze.com 2022-12-11 05:32 出处:网络
This program supposed to find command line arguments entered on Unix which ends with “.exe”.For some reason it doesn\'t work. Here is the code:

This program supposed to find command line arguments entered on Unix which ends with “.exe”. For some reason it doesn't work. Here is the code:

 int main( int argc, char* argv[] )
{
    for ( int i = 1; i < argc; i++)
    if( findExe( argv[i] ) )
      cout << argv[i] << endl;

  return 0;
}
bool findExe( char* argument )
{
  if ( strlen( argument ) >= 4 )
    {
      string testExe = ".exe";
      string initialWord=argument; //converts c-string to string
      string temp( initialWord,( initialWord.size() - 4 ),4 );//cr开发者_如何学运维eates temp with last four characters from initialWord

      if ( !temp.compare(testExe) )
        return true;
    }
  else
    return false;
}


Remove the else, I think (although I haven't compiled the code to check). In the case where the length is at least 4, but the string comparison returns non-zero, you reach the end of the function without returning. Your compiler should have warned you: turn on more warnings.


Your findExe function is has a branch that doesn't return a result....like Steve said, compiler should've warned you.


How about this?

bool findExe( char* argument )
{
    int n = strlen(argument);
    if (n < 4) return false;
    char* ext = argument[n-4];
    if (strcmp(ext, ".exe") == 0) return true;
    return false;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消