c++ - 从文件中获取字符而不是 getchar

标签 c++

我不知道如何从文件中而不是从 getchar() 中读取文本

字符串的计算熵

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include <string>
#include <iostream>
#include <cmath>
#include <fstream>
#include <cstring>
using namespace std;

double log2(double number) 
{
return log(number)/std::log(2.);
}

int main() {

unsigned long table[256], total = 0;
double entropy = 0;
char mychar;

string line;
ifstream myfile ("sometext.txt");
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
cout << line << '\n';
}

}
short i;

for(i=0; i<256; i++) 
table[i] = 0;

while(1)  
{  
mychar = getchar();

如何读取 myfile.txt ?

if (mychar==EOF) // ctrl Z 
{break;}
table[mychar]++;
}

for(i=33;i<127;i++)
if(table[i]) {
total += table[i]; 
entropy -= log2(table[i])*table[i];
}

entropy /= total;
entropy += log2(total);

printf("Total Characters: %6d\n",total);
printf("Entropy: %5.6f\n",entropy); 
}

最佳答案

使用 std::getline() 的循环读取行读取文件的内容!您实际上可以处理来自已读取的 std::string 的数据:

while (std::getline(myfile, line)) {
    std::cout << line << '\n';

    for (std::string::const_iterator it(line.begin()), end(line.end()); it != end; ++it) {
        unsigned char mychar = *it;
        ++table[mychar];
    }
}

内部循环遍历字符串 line 中的所有字符。它从当前处理的字符(即从 *it)获得一个 unsigned char,因为 char 可能是有符号类型并产生负值,这可能效果不太好。 ASCII 字符都是正数,但是,例如,我名字中的 u-umlaut ü 可能会变成负值;我想这对您的输入来说并不是真正的问题,但我更喜欢即使发生意外情况也能正常工作的代码。

在任何情况下,当 std::getline() 因为没有更多数据而失败时,此循环终止。如果您想再次读取数据,您需要打开一个新的std::ifstream 或重置std::ifstream你得到了:

myfile.clear();                        // clear error flags
myfile.seekg(0, std::ios_base::beg); // move to the start of the file

要将单个字符实际读取为 int,您可以使用

mychar = myfile.get();

不过,就我个人而言,我更倾向于使用迭代器读取字符:

for (std::istreambuf_iterator<char> it(myfile), end; it != end; ++it) {
    char mychar = *it; // well, you could keep using *it, of course
    // ...
}

关于c++ - 从文件中获取字符而不是 getchar,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20983356/

相关文章:

c++ - 如何编写 COM dll?

c++ - 为什么 `accumulate` 没有进入 C++20 的范围?

c++ - 如何在进程结束时保持 QProcess 执行的命令?

c++ - 如何在不使用 C++ 锁的情况下防止竞争条件?

c++ - 如何使用 pthreads 对类成员函数进行多线程处理?

c++ - 如何使用 C++ boost 库为特定线程定义堆栈大小?

c++搜索数字的数字

c++ - 如何将代码结果(在 void 函数内)写入 C++ 中的文本文件

c# - 参数依赖查找中的混淆?

c++ - %F 不返回任何输出