C++ std::string::compare
Check the end of a filename when listing receipts saved as PDFs.
A simple example
std::string::compare
- Start with "abc" and "bc"
- Do this Compare the ending
- Result Yes
#include <iostream>
#include <string>
int main() {
const std::string value = "abc";
const std::string other = "bc";
std::cout << ((value.size() >= other.size() && value.compare(value.size() - other.size(), other.size(), other) == 0) ? "yes" : "no") << "\n";
return 0;
}
yes
Syntax
label.size() >= 4 && label.compare(label.size() - 4, 4, ".pdf") == 0
Run these examples in C++
Save one example at a time as lesson.cpp. Use C++17 and a Unix-style shell.
c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lessonFind filenames with a receipt extension
A document picker displays receipt files alongside unrelated attachments. Filter by the expected ending so the clerk sees the right filenames before opening any of the files.
#include <iostream>
#include <string>
int main() {
const std::string label = "receipt.pdf";
std::cout << ((label.size() >= 4 && label.compare(label.size() - 4, 4, ".pdf") == 0) ? "yes" : "no") << "\n";
return 0;
}
yes
The final four characters match .pdf. A filename such as receipt.pdf.old would fail the check.
Find a class roster
A folder contains active exports alongside files with similar names and additional suffixes. Inspect the final filename or extension carefully before placing an entry in the report.
#include <iostream>
#include <string>
int main() {
const std::string value = "class.csv";
const std::string other = ".csv";
std::cout << ((value.size() >= other.size() && value.compare(value.size() - other.size(), other.size(), other) == 0) ? "yes" : "no") << "\n";
return 0;
}
yes
The final characters match the requested extension.
Exclude a backup export
A registry keeps an earlier export by adding an extra extension to its filename. Test the filename's final suffix before treating the file as part of today's import.
#include <iostream>
#include <string>
int main() {
const std::string value = "class.csv.old";
const std::string other = ".csv";
std::cout << ((value.size() >= other.size() && value.compare(value.size() - other.size(), other.size(), other) == 0) ? "yes" : "no") << "\n";
return 0;
}
no
The final extension is .old.
What to watch for
A filename suffix describes a naming convention. It cannot verify the contents of a file.