reading input from external files character by character

I'm trying to get this function to read characters from an external file one by one, but i cant seem to get it to work.

when i do "FileIn.get(Ch);" the Ch variable is always ASCII value -52 (the default) and when i switched that to "Ch=FileIn.get();" the Ch variable changed to ASCII -1(it should have been 'M') also every other time i did "Ch=FileIn.get()" it did not change the Ch variable.

can someone please explain what i'm doing wrong?

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
  int CountLineWordChar(CountsRecord & Data, char File[])
{
   char Ch;							 // current character in stream
   ifstream FileIn;	          // declare FileIn to be input file

    Data.CharCount = 0;
    Data.WordCount = 0;
    Data.LineCount = 0;
    FileIn.open("words.5");

    Ch=FileIn.get();
	++Data.CharCount;
   while(!cin.eof())
   {
		while (!isspace(Ch))
		{
			Ch=FileIn.get();
			++Data.CharCount;
		}
		++Data.WordCount;
		if (Ch=='\n')
			++Data.LineCount;
		Ch=FileIn.get();
		++Data.CharCount;
   }
   if (Data.CharCount>=1)
	   ++Data.LineCount;
   return 1;
Last edited on
On which line do you open your file?
it's in the main, should i include that code as well?
but FileIn in your CountLineWordChar() function has no relation to your stream in main(). It is not bound to any file at all.
Last edited on
ok, i edited the code block above to include opening (words.5 is the test file) but the result is still the same Ch is indefinitely ASCII -1
That usually means that your file is not correctly open or is empty. Check stream state with
1
2
if (!FileIn.good())
    std::cerr << "error opening file";

Some points to note:
1) .get() returns not char, but int.
2) Value of said int is 0-255 on success or EOF on failure
3) EOF usually equals to -1.
alright, there is an error opening the file. I'm not sure what it could be though. the file exists, it's in the correct place... is the problem in my code?
it's not open in your function open it in the function or pass it in as a parameter
maybe i'm opening it incorrectly then? is "FileIn.open("filename");" not the correct syntax?
You are opening it correctly. However I doubt that your filename is correct.
Do your file really have .5 extension? Or is it a regular text file which have happened to have a name words.5? If so, the filename should be words.5.txt
Topic archived. No new replies allowed.