InStreams and OutStreams. Anyone have any insigh they can share?

My task was to write a program that reads several lines of information from a data file and prints each word of the file on s separate line of an output file followed by the number of letters in that word. I also needed to print a count of words in the file on the screen when done.

Here is my code:
// File: Reading in file and printing out file> cpp

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;

#define inFile "H:\\Ch8_3.txt"
#define outFile "H:\\Ch8_3out.txt"

int main()
{
const char NWLN = '\n';
char next;
int charCount;
ifstream ins;
ofstream outs;

ins.open(inFile);
if (ins.fail())
{
cerr << "*** ERROR: Cannot open " << inFile << " for input." << endl;
return EXIT_FAILURE;
}
outs.open(outFile);
if (outs.fail())
{
cerr << "*** ERROR: Cannot open " << outFile << " for output." << endl;
return EXIT_FAILURE;
}

charCount = 0;
while (next !=NWLN)
{
outs.put(next);
charCount++;
ins.get(next);
}

outs.put(NWLN);
cout << "Letter Count = "<< charCount << endl;
ins.get(next);

return 0;
}

The code does not read the data file, I can't find the reason why, and this has bothered me for three weeks. Not even my professor for my programming class couldn't find the issue. Anyone want to give a try?
The code does not read the data file
What exactly is the problem? File not open or something?

One problem is that next is not initialized. You cannot predict what the content is. If next is accidentally '\n' you won't get into the while loop

Please use code tags: [code]Your code[/code]
The problem is that the code will not open and in file to read a personal data file, the code by its self can be debugged without issues. But it continues to state the exit failure for the InFile.
And you're positive that the file you're reading from exists and is named correctly? It works fine for me when using a different file name that I have stored on my own computer, regardless of whether or not I'm using a mapped drive or a file in the same folder as the .cpp file.
Yes I did name it from a file that exist, but I will try rename it.

Okay I tried renaming, I created a file from notepad and one from Microsoftword with the name but still failed.
Last edited on
That is definitely quite odd.

Try changing your code to #define inFile "name.txt" and place your text file in the same folder as your .cpp file. We'll try and take as many factors out of this equation as we can.
Topic archived. No new replies allowed.