Checking file extension

Hi, I'm writing a program that will output text and save it into a ".txt" file. I ask the user to to name the output file, but I want to be able to check if they enter it as "*.txt" or simply as the name without the ".txt".

I know I need an if statement to check the last four characters in the string - the ".txt" part. If it has the ".txt" then I can leave the filename alone, and if not, then append ".txt" to the filename.

Here's what I have so far:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
string
inputfile()
{
    string text ="";;
    string filename = "";;
    ifstream input;

    cout << "*** NOTE: File must be in current directory. ***\n\n";
    cout << "Enter the filename: " << endl;
    cin >> filename;

// Here's where the if statement needs to go.
    filename += ".txt"; // This will work if the filename doesn't have the ".txt"

    cout << filename;

    cin.ignore();

    input.open (filename.c_str());
    getline (input, text);
    input.close();

    return (text);
}


Can anyone help me out here?
Cheers.
closed account (o3hC5Di1)
Hi there,

No expert here, but I would go about using these two functions:

http://www.cplusplus.com/reference/string/string/find_last_of/
http://www.cplusplus.com/reference/string/string/substr/

The first to find the position of the last occurrence of '.', the second to get 3 characters after that position, which should be your extension.

Hope that helps.

All the best,
NwN
Ah, thanks a million! I'll take a look at these and get back to you!
-M
Topic archived. No new replies allowed.