I am a beginner at C++ programming. I am trying to write a code that will read from a user-specified input file and write any vowels or newline characters in the file to an output file called "vowels_[input file name]". The code below seems to work for opening and creating the files, but it is not outputting correctly for some reason. Every different configuration of output methods I have tried all result in a blank output file. What am I missing here?
For one, your check on line 52 is wrong. You evaluate ('a'||'A'||'e'||'E'||'i'||'I'||'o'||'O'||'u'||'U'||'\n') which is true, by the way, and compare it to c. I think you meant to check if c is any of those characters, which is more like c == 'a' || c == 'A' || ...
One tip: don't keep dynamically constructing those C-strings to pass around. Just give the file streams the strings directly or .c_str() if you aren't using the latest version of C++.
With respect to your actual problem, I'd only open the file once; just check if it worked and if it does, use that stream rather than opening a second which could fail separately.
#include <iostream>
#include <fstream>
#include <cstring>
#include <string>
usingnamespace std;
int main()
{
string fileName;
bool flag = false;
char c = ' ';
do
{
//Get file name.
cout << "Please enter file name, then press enter: ";
cin >> fileName;
//Check that the name was entered properly, otherwise repeat loop.
ifstream ifile(fileName.c_str());
if(ifile)
flag = true;
else
cout << endl << fileName << " does not exist." << endl << endl;
}while(!flag);
//Open the file for reading.
ifstream ifile(fileName.c_str());
ifile.open(fileName.c_str(), ios::in);
//Create file name for output.
fileName = "vowels_" + fileName;
//Open file for writing.
ofstream ofile(fileName.c_str());
ofile.open(fileName.c_str(), ios::out);
//Loop through input file char by char.
while(ifile.get(c))
{
//If the current char is a vowel or newline, write to output file.
if(c == 'a'||c == 'A'||c =='e'||c =='E'||c =='i'||c =='I'||c =='o'||c =='O'||c =='u'||c =='U'||c =='\n')
ofile.put(c);
}
//Close files.
ifile.close();
ofile.close();
return 0;
}
Still gettting a blank output file.
Side note: If I try to only declare the ifstream once (in the initial loop to test) i get the error: "ifile was not declared in this scope". Is there another way for me to test the user-input without declaring a second ifstream such as in your suggestion?
You could declare just one fstream and instead of using the constructor to open the file, use .open().
On that note, now that I've looked again, you are opening the files twice! The first time in the constructor and again immediately after with open(). Try removing the unnecessary calls to open().