1

I want to compare the last 3 chars of this one char and compare this with another char and if it's true, it should come to an action.

const char* find = strrch(filename, '.');
if(find != (char*) ".aac")
{
    //do this and this
}

But it doesn't work. The filename is an audio file and the char is like music.aac, and I want to do something only when the last 3 chars aren't aac.

Zong
  • 6,160
  • 5
  • 32
  • 46
user2492388
  • 151
  • 6
  • 15

4 Answers4

1

You're comparing the address of the . character with the address of a string literal, which will never be equal. You'll need to use a library to compare string values, either C++:

#include <string>

std::string find = ...
if (find != ".aac")

or C:

#include <cstring>

if (std::strcmp(find, ".aac") != 0)
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
0

strcmp() is needed to compare char *, std::equal, converting the char * to std::string and using the overloaded ==, and writing your own for loop are other options.

yizzlez
  • 8,757
  • 4
  • 29
  • 44
0

Given that you are trying to compare char* pointers instead of actually comparing strings, I must recommend you to read a good C++ book first. You can pick one from The Definitive C++ Book Guide and List

As for comparing last N character of the string, there are many ways of doing this. Here is just one to get you started:

#include <string>
#include <cctype>
#include <algorithm>
#include <iterator>
#include <iostream> // For example output only.

bool ends_with(
    const std::string& str, const std::string& with,
    bool ignore_case = false
) {
    if (str.length() < with.length())
        return false;
    const auto offset = str.length() - with.length();
    return (
        ignore_case ?
        std::equal(
            std::begin(str) + offset, std::end(str), std::begin(with),
            [](char a, char b){ return ::toupper(a) == ::toupper(b); }
        ) :
        std::equal(std::begin(str) + offset, std::end(str), std::begin(with))
    );
}

int main() {
    std::string filename{"myfile.txt"};
    if (ends_with(filename, ".txt"))
        std::cout << "It is a text file!\n";
    if (ends_with(filename, ".TXT"))
        std::cerr << "Something is wrong :(\n";
    if (ends_with(filename, ".TXT", true))
        std::cout << "Yeah, it is really a text file!\n";
}

This is a modified version taken from here. I have found it in 5 seconds using GitHub code search, and there are literally thousands of results for C++, so you might want to check it out, read and try to understand the code, that would help you learn C++.

Hope it helps. Good Luck!

Community
  • 1
  • 1
0

for 3 remaining chars i would do it quickly by char, no need for strings

const char* find = strrchr(filename, '.');
if(!(find!=0 && *(++find)=='a' && *(++find)=='a' && *(++find)=='c'))
   printf("file %s is not .aac\n", filename);

btw. you got me for a sec whit leaving out the trailing r (strrchr) :-)

Alex
  • 1
  • 1