Attempting to get character from an input file - c++

I'm trying to get characters from an input file but I can't really get it to work, anyone who could help me on this one? I apologize in advance for the formatting, it confused me.
open_input_and_output_file basically checks whether or not you can open the files and in OTP I'm attempting to get every single character from one file to the other. As I couldn't get it to work I first tried displaying those characters in the console application, but that is also not working.
Any help would be appreciated, I hope the information provided is enough.
bool open_input_and_output_file(ifstream& infile, ofstream& outfile)
{
//Precondition: True
assert(true);
//Postcondition: Inputfile and outputfile have either been opened succesfully or you have been notified of it not opening succesfully.
string inputfile;
string outputfile;
cout<<"\nPlease enter an input-file name (no spaces): ";
cin>>inputfile;
cout<<"NOTE: Input-file name and output-file name can NOT be the same!"<<endl;
cout<<"Please enter an output-file name (no spaces): ";
cin>>outputfile;
if(inputfile != outputfile)
{
cout<<"Input-file name and output-file name are not the same! Good job on reading!"<<endl;
ifstream infile(inputfile.c_str());
if(infile)
cout<<"Input-file: "<<inputfile<<" was opened succesfully!"<<endl;
if(!infile)
cout<<"Inputfile: "<<inputfile<<" could not be opened!"<<endl;
ofstream outfile(outputfile.c_str());
if(outfile)
cout<<"Output-file: "<<outputfile<<" was opened succesfully!"<<endl;
if(!outfile)
cout<<"Outputfile: "<<outputfile<<" could not be opened!"<<endl;
}
else
{
cout<<"Input-file name and output-file name are the same!"<<endl;
cout<<"Opening has failed!"<<endl;
}
return 0;
}
void OTP(ifstream& infile, ofstream& outfile)
{
int choice;
char character;
unsigned int r;
srand(r);
cout<<"\nPlease enter 0 to encrypt or 1 to decrypt: ";
cin>>choice;
if(open_input_and_output_file(infile,outfile))
{
infile.get(character);
cout<<character;
}
}

I would say the error is here
cout<<"Input-file name and output-file name are not the same! Good job on reading!"<<endl;
ifstream infile(inputfile.c_str());
should be
cout<<"Input-file name and output-file name are not the same! Good job on reading!"<<endl;
infile.open(inputfile.c_str());
You make the same mistake with outfile.
ofstream outfile(outputfile.c_str());
should be
outfile.open(outputfile.c_str());
You pass infile and outfile as parameters to your open_input_and_output_file function, but then you declare them again inside the function. So when you open the files you aren't using the streams that were passed to open_input_and_output_file, instead you are using streams that are local to that function. The streams passed to open_input_and_output_file stay closed.

Related

Input validation of opening a text file in C++

I am building an input validation function that takes the input of the user and tries to open that file. and repeats if user is not entering the correct format. the correct format is:
test1.txt
My function works if I write correct format in the first run, but after the second run it keeps printing the error message although I am writing the write format to be opened. I have tried to clear the input "cin" and "filename" after taking the input but it did not work. Any ideas ?
string getFileInput()
{
string filename;
fstream file;
cout << "Please enter the name of the file: ";
getline(cin, filename);
file.open(filename.c_str());
while(!file.is_open())
{
file.clear(); file.ignore();
cout << "File name is incorrect, please enter again: ";
cin.clear(); cin.ignore();
getline(cin, filename);
file.open(filename.c_str());
}
// Extra condition. Empty file
if (file.eof())
{
cout << filename << " is an empty file." << endl;
}
file.close();
return filename;
}
I could reproduce and fix.
The problem is caused by cin.ignore(). According to cppreference:
... the next available character c in the input sequence is delim
So ignore will read the next line, up to the newline, and leave that newline alone. And the following getline can only read an empty string!
By the way, using a non opened fstream (file) for ignore and clear is at least useless and could be harmlfull because those methods are expected to be called on an open stream. And using cin.clear() is useless too and can be harmfull: if for any reason you have a read error (because you reached an end of file for example), you will consistently clear the error condition and try to read again when you should abort.
Finally, the eof condition is only set after a read returned nothing because of the end of file. It is never set when opening an empty file, nor if you could successfully read up to the end of file.
So the function should boil down to:
string getFileInput()
{
string filename;
fstream file;
cout << "Please enter the name of the file: ";
getline(cin, filename);
if (! cin) {
// test the error immediately and before using filename!
cerr << "read error: aborting...\n";
return "";
}
file.open(filename.c_str());
while(!file.is_open())
{
cout << "File name is incorrect, please enter again: ";
getline(cin, filename);
if (! cin) {
// test the error immediately and before using filename!
cerr << "read error: aborting...\n";
return "";
}
file.open(filename.c_str());
}
file.close();
return filename;
}

ifstream is.open() acting like it's not reading the file

//Prompts user for a file name and stores it
string fileName;
cout << "Enter the file name: ";
cin >> fileName;
ifstream inFile (fileName);
inFile.open(fileName);
//Prompt the user until they give the name of a file that can be opened
bool validFileName = false;
while(validFileName == false)
{
if(inFile.is_open())
{
validFileName = true;
}
else
{
cout << "Please enter a valid file name: ";
cin >> fileName;
ifstream inFile;
inFile.open(fileName);
}
}
//this block prints to the terminal, so it's opening
if(inFile.is_open())
{ cout << "It works! \n"; }
I am trying to create a program that will work with a file, but there needs to be a section that checks to see if the file that the user types in is an actual file that the program can open. I've tried a few different ways to write the while loop, because it needs to keep asking until it receives a valid file. I have the valid file name "input.txt", but even when I type that into the terminal it continues to print the error message. I have tried to type the file name with and without quotes, so I'm not sure what it is caught up on. I know it is opening the file, because I added a second check afterward and it appears that it's opening, so I think it's an issue with how I have the error check statement written?
The problem is that you are using
ifstream inFile;
inFile.open(fileName);
in the loop. The variable in the loop hides the variable of the same name outside the loop. Remove the first of those lines.
FWIW, you can simplify your code to:
ifstream inFile (fileName);
while(!inFile)
{
// Prompt the user until they give the name of a file that can be opened
cout << "Please enter a valid file name: ";
cin >> fileName;
inFile.open(fileName);
}
if(inFile)
{
cout << "It works! \n";
}
In:
ifstream inFile (fileName);
inFile.open(fileName);
The file is opened on the first line.
Reopening it is redundant.
Also in the loop you declare a temporary variable inFile which goes out of stop at the end of the else statement. Make sure to declare it only once at the outmost scope you would like to use it.

c++ fstream regarding reading file on certain lines of .txt files

So I am very new to c++ and on an assignment I have for school I am making a program that uses fstream to put in userIds and passwords into a text file and I am not sure why this will not work when trying to confirm that the username and pass are correct
int login()
{
fstream accountFile2;
bool confirm;
string userID;
string accountPass;
string IDConfirm;
string PassConfirm;
accountFile2.open("accountfile.txt",ios::in | ios::out);
cout<<"Login!\n Enter your User ID: "<<endl;
cin>>userID;
cout<<"Please enter your account's password\n";
cin>>accountPass;
accountFile>>IDConfirm;
accountFile>>PassConfirm;
accountFile2.close();
if((userID == IDConfirm) && (accountPass == PassConfirm))
{
confirm = 1;
cout<<"success";
}
else
{
confirm =0;
cout<<"invalid id/pass";
}
return confirm;
}
Assuming accountFile and accountFile2 is a typo, it works for me (and the compiler).
Double check that the file exists and contains right data. Also beware, that std::cin >> variable for variable of type std::string will read only one word (will stop reading when it finds whitespace). If you want to read whole line, use std::getline(std::cin, variable) instead.

File I/O in Functions?

I am trying to figure out how to correctly make a File I/O Function in C++, however I can not seem to get it to work properly. I am currently not at the level to use vectors yet.
How would I go about changing this code to make it into a working function?
If anyone could point me in the right direction I would be grateful.
Here is the Prototype:
string obtain_inFileName(void);
The Function Call:
inputFileName = obtain_inFileName();
The Function:
string obtain_inFileName(void)
{
string inFile;
cout<<"Enter the name of the input file: ";
cin >> inFile;
cout << endl;
return (inFile);
}
Well, the closest thing I could consider working for your case would be
string obtain_inFileName (ifstream &inFileName) {
std::string inputFileName;
cout<<"Enter the name of the input file: ";
cin>>inputFileName;
inFileName.open(inputFileName.c_str());
return inputFileName;
}
Not claiming, that this is a good implementation!

Asking for an input file until it is correct in c++

I am trying to read a file in c++. I ask the filename to user, if file exists i open it but if it does not exist i keep asking until a valid filename is entered. But when user enters a wrong file first, even though it enters a valid filename after that my program recognizes it as false. Here is my code:
ifstream input;
string filename;
cout<<"Enter the file name";
cin>>filename;
input.open(filename.c_str());
while(input.fail())
{
cout<<"Incorrect filename, please enter again";
cin>>filename;
input.open(filename.c_str());
}
Can anyone help? Thanks
You need to clear the input when it is entered wrong. Try this:
ifstream input;
string filename;
cout<<"Enter the file name";
cin>>filename;
input.open(filename.c_str());
while(input.fail())
{
input.clear();
cout<<"Incorrect filename, please enter again";
cin>>filename;
input.open(filename.c_str());
}