这是我到目前为止所拥有的;我试图在文本文件中有一个具有所有字符和空格概率的数组,但我的数据类型有问题。
int main()
{
float x[27];
unsigned sum = 0;
struct Count {
unsigned n;
void print(unsigned index, unsigned total) {
char c = (char)index;
if (isprint(c)) cout << "'" << c << "'";
else cout << "'\\" << index << "'";
cout << " occured " << n << "/" << total << " times";
cout << ", propability is " << (double)n / total << "\n";
}
Count() : n() {}
} count[256];
ifstream myfile("C:\\text.txt"); // one \ masks the other
while (!myfile.eof()) {
char c;
myfile.get(c);
if (!myfile) break;
sum++;
count[(unsigned char)c].n++;
}
for (unsigned i = 0; i<256; i++)
{
count[i].print(i, sum);
}
x[0] = count[33];
int j=68;
for(int i=1;i<27;i++)
{
x[i]=count[j];
j++;
}
return 0;
}
答案 0 :(得分:2)
#include <iostream>
#include <fstream>
#include <cctype>
using namespace std;
double probabilities[256]; // now it can be accessed by Count
int main()
{
unsigned sum = 0;
struct Count {
unsigned n;
double prob;
void print ( unsigned index, unsigned total ) {
// if ( ! n ) return;
probabilities[index] = prob = (double)n/total;
char c = (char) index;
if ( isprint(c) ) cout << "'" << c << "'";
else cout << "'\\" << index << "'";
cout<<" seen "<<n<<"/"<<total<<" times, probability is "<<prob<<endl;
}
Count(): n(), prob() {}
operator double() const { return prob; }
operator float() const { return (float)prob; }
} count[256];
ifstream myfile("C:\\text.txt"); // one \ masks the other
while(!myfile.eof()) {
char c;
myfile.get(c);
if ( !myfile ) break;
sum++;
count[(unsigned char)c].n++;
}
for ( unsigned i=0; i<256; i++ ) count[i].print(i,sum);
return 0;
}
我建议了各种修改 - 谢谢!
现在,谁找到了4种获取实际概率的方法?
答案 1 :(得分:0)
您正在分配大小为1000000
100万个字符的缓冲区。
char file[1000000] = "C:\text.txt";
这不好,因为缓冲区中的额外值不能保证为零,可以是任何值。
对于Windows来读取文件,您需要这样的东西。我不会给你解决方案,你需要学习使用msdn和文档来完全理解这一点::
您需要首先在SDK中添加#include <windows.h>
标头。
请在此处查看此示例:http://msdn.microsoft.com/en-us/library/windows/desktop/aa363778(v=vs.85).aspx
此示例将文件附加到另一个文件。您的解决方案将类似,而不是将列表写入其他文件,处理缓冲区以增加局部变量并更新表的状态。
不要为缓冲区设置一个大数字,因为存在没有足够缓冲区空间的风险,因此存在溢出。你应该这样做:
重复,直至到达文件末尾
while (ReadFile(hFile, buff, sizeof(buff), &dwBytesRead, NULL)
&& dwBytesRead > 0)
{
// write you logic here
}