There is a problem reading the file.

I completely enter the file address for the code test.
But ''else'' is constantly executed. What could be the problem? The test file and the code itself with the whole solution are in the same folder.

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
  #include <iostream>
#include <stdio.h>
#include <string>
#include <ifsteam>
#include <ofstream>

using namespace std;

int main()
{
	
	cout << "Enter file name or path to it: " << endl;
	char* path = new char[256];
	cin >> path;

	FILE* in;
	
	if ((in = fopen(path, "r")) != NULL) {
		
		fseek(in, 0L, SEEK_END);
		int len = ftell(in);

		
		fseek(in, 0L, SEEK_SET);
		int stats[256] = { 0 };

		
		int ch = 0;
		while (fscanf(in, "%c", &ch) != EOF)
		{
			stats[ch]++;
		}

		double h = 0;
		double p[256];

		
		for (int i = 0; i < 256; ++i)
		{
			if (stats[i] == 0) continue;
			p[i] = static_cast<double>(stats[i]) / len;
			h += (log10(1.0 / p[i]) / log10(2.0)) * p[i];
		}

		cout << h << endl;
	}
	else
	{
		cout << "File not found";
	}

	return 0;
}
Last edited on
Write exactly what you are typing into the program.
- Does your path contain spaces?
- Is it a relative path or an absolute path?

Using cin >> with a char array is dangerous because there is no way to limit the size of the buffer you're feeding into. Using getline will prevent this buffer overflow and allow for spaces.

http://www.cplusplus.com/reference/istream/istream/getline/
1
2
3
  char name[256];
  std::cout << "Please, enter your name: ";
  std::cin.getline (name,256);


Better yet, since you're already using C++, use string:
1
2
3
4
5
6
7
8
string filename.
getline(cin, filename);

// ...

ifstream in(filename);

// ... 
Last edited on
Okay, I'll use another input command. Thanks.
Using cin >> with a char array is dangerous because there is no way to limit the size of the buffer you're feeding into.


Use >> setw(n) to only extract n - 1 chars.
I assume chebyrek's issue was the spaces, but cool, I didn't know that was a thing you could do on the input side. I can't find whether or not that adds a null-terminator, so I guess you should do it yourself just in case.
Last edited on
>> setw(n) specifies the total size of the available buffer including the terminating null-char. The resultant char array is null-terminated in all cases. So a max of n - 1 chars are input.
Last edited on
Oh right, cin >> char_array would add the null terminator already. Thanks.
Topic archived. No new replies allowed.