Checking String for File Extension(s)?

I am having trouble getting my program to check a string for more than one file extension.

The following code:


void Check_ext(const string& filename)
{
int i = filename.find(".jpg");

while(i == string::npos)
{
cout<<"Invalid input: must end with '.jpg', '.jpeg', or '.gif'"<<endl;
cin.clear();
cin.ignore(1000,'\n');
cin>>filename;
i = filename.find(".jpg");
}
}

Works fine if all I need is to check for the '.jpg' file extension, but I need to check for multiple file extensions(like .gif,etc.). How would I go about doing that?
I would do it something like this, though you could take the code out of main() and into another function if that is your preference.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
bool Check_ext(const string& filename);

int main()
{

    string filename;
    cout << "Please enter name of image file: " << endl;
    cin >> filename;

    while (!Check_ext(filename))
    {
        cout << "Invalid input: must end with '.jpg', '.jpeg', or '.gif'" << endl;
        cin.ignore(1000,'\n');
        cin >> filename;
    }

    return 0;
}

bool Check_ext(const string& filename)
{
    size_t pos = filename.rfind('.');
    if (pos == string::npos)
        return false;

    string ext = filename.substr(pos+1);

    if (ext == "jpg" || ext == "jpeg" || ext == "gif")
        return true;

    return false;
}
That makes perfect sense! Thank you for your help Chervil.
Topic archived. No new replies allowed.