This code is not going to work a better alternative is -
1 2 3 4 5 6 7 8 9 10 11 12 13
string name;
string ext=".txt";
string f_name;
cout << "enter file name: ";
getline (cin, name);
f_name=name+ext; // creating the name of the file
ofstream myfile(f_name.c_str()); // creating file
myfile<< " This is the file"; // this message will copy into the file
and the file will be there with desired name.
include cstdlib also. There will be better way then this also but it will also do.
...
getfilename(f_name);
...
void getfilename(std::string& fname)
{
/*
* Check for a file extension (iterate over the string and find the first
* '.'. We don't check fname[0] for a '.' because hidden files often
* begin with one).
*/
for (size_t i = fname.length(); i > 0; --i) {
if (fname[i] == '.')
break;
}
if (i >= 1) /* Then there were no '.'s in the string */
fname += ".txt"; /* Append a default file extension */
/*
* Note: We don't have to return anything because fname was passed by
* reference.
*/
}
".hidden_file"
012345678
s <- there we start so we dont care about the leading
or just search for ".txt"... but that lacks the check for other extensions...
(i know this is not the most beautiful solution, but Afaik the usual files wont named like "..txt" or?^^... "if it is ".a.txt" then it´s fine - i hope :D)...
to blackcoders suggestion: clover leaf, this is fine, because You are able to open files without extensions, too...
Why start four characters from the start? For all we know, the system the program is running on allows filenames of length 0-n and the same for file extensions. The last '.' is the only one relevant to the file extension, hence why my loop went backwards.
You could do this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/*
* Find the last '.'. If it is at the beginning or end of the string,
* we append ".txt". Otherwise, we know a file extension already exists.
* Examples:
*
* ".hiddenfile" -- attach .txt
* "somefile." -- attach .txt
* "somefile.ext" -- ignore
*/
void getfilename(std::string& fname)
{
size_t pos = fname.find_last_of(".");
if (pos == 0 || pos == (fname.length() - 1))
return;
else
fname += ".txt";
}