Hi!
What is the easy way to create a function in C++ which will return the basename from a string i.e.
from "C:/tutu/tata/test" I want to get "test"
Thanks!
Hi!
What is the easy way to create a function in C++ which will return the basename from a string i.e.
from "C:/tutu/tata/test" I want to get "test"
Thanks!
You could try string::rfind, searches a string starting from the back. Check out this totally awesome code
Code:#include <string> #include <iostream> int main(int argc, char *argv[]) { //You'll note how cool it is the lines line up std::string stuff("C:/woot/rawr/whatev/test"); std::string::size_type pos = stuff.rfind("/"); if(pos != std::string::npos) std::cout << stuff.substr(pos + 1, stuff.length() - pos + 1) << "\n"; else std::cout << "Invalid path\n"; return 0; }
Thanks I tried that but I get the same in input and ouput doing
Maybe it's the "/"?Code:int pos = name.rfind("/"); std::string basename = name.substr(pos + 1, name.length() - pos + 1);
Actually it is more complicated because I have
"C:\SMG\Projects\BoreholeTut\GRDFILE.grd\D1SF.grid " and I want to obtain "D1SF"
Code:#include <string> #include <iostream> int main(int argc, char *argv[]) { // You'll note the failure to make aesthetically awesome code here <sad> std::string stuff("C:\\SMG\\Projects\\BoreholeTut\\GRDFILE.grd\\D1SF.grid"); std::string::size_type pos[2]; pos[0] = stuff.rfind("\\"); pos[1] = stuff.rfind("."); if(pos[0] != std::string::npos && pos[1] != std::string::npos) std::cout << stuff.substr(pos[0] + 1, stuff.length() - pos[1] - 1) << "\n"; else std::cout << "Invalid path\n"; return 0; }
if I put a single slash "\" in the rfind search as it should be (you put two slashes in your example) I get a compile error "newline constant" why?
Something about, maybe, escape sequences: http://www.cppreference.com/escape_sequences.html