How to check if string ends with .txt

Viewed 40017

I am learning basic C++, and right now I have gotten a string from a user and I want to check if they typed the entire file name (including .txt) or not. I have the string, but how can I check if the string ends with ".txt" ?

string fileName;

cout << "Enter filename: \n";
cin >> fileName;

string txt = fileName.Right(4);

The Right(int) method only works with CString, so the above code does not work. I want to use a regular string, if possible. Any ideas?

12 Answers

This should do it.

bool ends_with(const std::string & s, const std::string & suffix) {
     return s.rfind(suffix) == s.length() - suffix.length();
}

Verify here

Since C++17 you can utilize the path class from the filesystem library.

#include <filesystem>

bool ends_with_txt(const std::string& fileName) {
    return std::filesystem::path{fileName}.extension() == ".txt";
}
Related