[英]Compare characters at the end of the string C++
該程序應該查找在Unix上以“ .exe”結尾的命令行參數。 由於某種原因,它不起作用。 這是代碼:
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 );//creates temp with last four characters from initialWord
if ( !temp.compare(testExe) )
return true;
}
else
return false;
}
我認為應該刪除else
(盡管我還沒有編譯要檢查的代碼)。 如果長度至少為4,但字符串比較返回的非零值,則無需返回就可以到達函數的末尾。 您的編譯器應該已經警告您:打開更多警告。
您的findExe函數具有一個不返回結果的分支。...就像史蒂夫所說的那樣,編譯器應已警告您。
這個怎么樣?
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.