Hello people!
I've been stuck on this assignment for a few days now and even though i've found some helping threads that handles basicly the same subject i haven't been able to find quite what im looking for, so i've decided to ask for help. :)
What i need to do is to write a function where the user can type in a filename, this will open the file, however, im also supposed to check the filename for ".txt" or ".TxT" (or other variations), if ".txt" is found, the program will read the file, otherwise it will append ".txt" to the filename and then read the file.
I already know how to open the file, what i need help with is really the if-statement that searches for .txt and if it isnt found, it will add .txt to the filename. My teacher recommended using .rfind() and .append(), but i cant figure out how to write a good if-statement.
this is what i've got so far :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
|
#include <string>
#include <cctype>
#include <iostream>
#include <fstream>
#include <cmath>
#include <cstdlib>
using namespace std;
int main()
{
string txt = ".txt";
string filename;
cout << "Ange filename: ";
getline( cin, filename );
filename.length();
ifstream fin( filename.c_str() );
str.append(txt);
if ( !fin )//this is the if-statement i would like to change to a loop(?) that
{ //searches for .txt and if it isnt found ".txt" should be added.
cout << "Filen kunde inte öppnas"
<< endl;
exit( EXIT_FAILURE );
}
char c;
while ( fin.get(c) )
{
cout << c;
}
return 0;
}
|
Hope someone can help, thanks in advance!