for an example, i have an array with a filename
Code: Select all
char fname = "test.txt"
is there anyway to just return ".txt"?
Thank you!
Personal computing discussed
Moderators: renee, SecretSquirrel, just brew it!
char fname = "test.txt"
#include <string>
// ...
std::string s = "example.txt";
std::string ext = (s.find('.') != std::string::npos) ? s.substr(s.find('.')+1) : "";
string fname;
void main(int argc, char **argv)
{
cin>>fname;
}
#define MAX_EXT 4
void main(int argc, char **argv)
{
char fileExt[MAX_EXT];
short i;
//Look for the string starting point since we are doing a reverse lookup.
//Then go from the end of the string to the start looking for '.'
//Does not check for null string.
i = strlen(argv[0]); //Looks at only the first char string in the array of arguments, gets the end count of string
while(i > -1 && argv[0][i] != '.') i--; //Look for the first '.' in from end of string
if (i > -1) strcpy(fileExt, &(argv[0][i+1])); //Copy the extension only.
}
#include <iostream>
using namespace std;
int main(int argc, char **argv)
{
if (argc < 2)
{
cout << "no argument specified\n";
return 1;
}
string fname = argv[1];
string efname;
int dot = fname.find_last_of('.');
if (dot != string::npos)
{
efname = fname.substr(dot);
cout << "Result = \"" << efname.c_str() << "\"\n";
}
else
cout << "no dot in argument\n";
return 0;
}
Craig P. wrote:You also need to include <string> in jbi's code -- it's a library implementation feature that it worked without it.
Also, it shouldn't be necessary to insert using the c_str() member, you should be able to insert the string directly.
just brew it! wrote:Also, it shouldn't be necessary to insert using the c_str() member, you should be able to insert the string directly.
Without the c_str() it compiles OK under g++, but gives a compilation error under VC++. (The error message is: "error C2679: binary '<<' : no operator defined which takes a right-hand operand of type 'class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >' (or there is no acceptable conversion)" )