program always outputs "question mark box" to console

Hi guys

Im not quite sure what is going on here, i've tried google but to no avail, maybe im just not searching right.

But i've made a little program to prints the content of a .txt file to the console. but for some reason it always outputs this weird questionmark thingy at the end.
It has no problem reading special characters specifik only to my country. i.e "æ"

Any ideas to why this appears?

OUTPUT:
casper@x220:~/code/readfile$ ./rdf test.txt
-----------------------------------
line 1 kartoffler
majs og ærter

-----------------------------------
There are 6 words in this document.
-----------------------------------


CODE:
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <stdio.h>
#include <ctype.h>
#include <iostream>
#include <unistd.h>

using namespace std;

int main(int argc, const char *argv[])
{
	if (argc == 1)
	{
		cout << "You need to specify a file." << endl;
		return 0;
	}
 
	int c;
	int t, wcnt = 0;
	FILE* file;
	file = fopen(argv[1], "r");		

	if (file == NULL)
	{
		cout << "Failed to load file" << endl;	
		fclose(file);
		return EXIT_FAILURE;
	}
	else
	{
		cout << "-----------------------------------" << endl;
		
		do
		{
			c = getc ( file );
			printf ("%c", c );
			usleep(1000);
			
			if (isspace(c))
			{
				t++;
				
				if ( t <= 1)
					wcnt++;				
			}
			
			if (!isspace(c))
				t = 0;
				
		} while (c != EOF);

	}
	
	cout << "\n-----------------------------------" << endl;
 	cout << "There are " << wcnt << " words in this document." << endl;
	cout << "-----------------------------------" << endl;
	
	fclose(file);
	return 0;
}
Last edited on
The problem is that you don't check if getc has returned EOF until after you have printed the character.

Instead of
1
2
3
4
5
do
{
	c = getc(file);
	...
} while (c != EOF);

Consider doing like this instead
1
2
3
4
while ((c = getc(file)) != EOF)
{
	...
}
Peter87, thanks mate. Worked like a charm :D
Topic archived. No new replies allowed.