我正在尝试使用 ifstream 将此 C 函数的等效代码执行到 c++ 中

I am trying to do the equivalent code of this C function into c++ with ifstream

本文关键字:代码 执行 c++ 函数 将此 ifstream      更新时间:2023-10-16

此函数读取一个包含字符大小数字的文本文件(文本文件在另一个程序中以字符编写),我需要在读取后将它们转换为整数。由于我的程序的其余部分都在C++,我也想在C++中获取此功能。我遇到的最大麻烦是面包大小(字符)

void VAD_Selector(vector<int>& x){
    FILE *ptr = NULL;
    if ((ptr = fopen(USABLE_VAD, "r")) == NULL) {
        cout << "Error opening VAD file" << endl;
        exit(0);
    }
    short mode = 0;
    char VAD_input[2] = "0";
    x[0] = 0;
    int i = 1;
    while (fread(VAD_input, sizeof(char), 1, ptr)) {
        mode = (short)atoi(VAD_input);
        if (mode != 1)
            x[i] = 0;
        i++;
    }
    fclose(ptr);
}

这是输入文本文件的样子:

00000000000000000000000000000000000001111111111111111111111111111111111111111111111

没有输出,但我想做的是将所有数据从文本文件获取到 x 向量中(x[0] 始终为 0)

这是我尝试过的:

ifstream ptr;
ptr.open(USABLE_VAD);
if (!ptr.is_open()) {
    cout << "Error opening VAD file" << endl;
    exit(0);
}
else {
    x[0] = 0;
    int i = 1;
    char c[2] = "0";
    while (!ptr.eof()) {
        ptr >> c;
        x[i] = atoi(c);
        cout << x[i];
                    i++;
    }

}
ptr.close();

我在ptr << c之前在VS2015中收到此错误:

Algo_gen.exe: 0xC0000005:访问冲突读取位置0x6CB95C28中引发0x60C4B8BA的异常 (msvcp140d.dll)。

如果存在此异常的处理程序,则可以安全地继续该程序。

我更改了 while 循环条件并使用了 c - '0' 并且它可以工作。谢谢大家。如果它可以帮助其他人,有我的解决方案:

void VAD_Selector(vector<int>& x){
ifstream ptr;
ptr.open(USABLE_VAD);
if (!ptr.is_open()) {
    cout << "Error opening VAD file" << endl;
    exit(0);
}
else {
    x[0] = 0;
    int i = 1;
    char c = '0';
    while (ptr >> c) {
        x[i] = c - '0';
        i++;
    }
}
ptr.close();

}

我认为你想要的是这样的东西

std::vector<int> VAD_Selector(std::string const&file_name)
{
  std::ifstream input(file_name);
  if(!input.is_open())
    throw std::runtime_error("failed to open file '"+file_name+"' for reading");
  std::vector<int> data = {0};
  for(char c; input >> c;)
    data.push_back(int(c-'0'));
  return data;
}
如果我

是对的,您正在尝试在C++中实现 C 函数VAD_Selector(vector<int>& x),并且在C++中实现代码行while(fread(VAD_input , sizeof(char), 1, ptr))时遇到了麻烦。右?

我认为上面fread函数是用 C 实现的,你可能有一个它的头文件。由于C++中的名称重整,您必须在C++文件的开头添加以下代码(extern "C"),才能在C++程序中使用函数fread。但是您仍然有另一个问题,即文件指针ptr,函数fread中的第 4 个参数。现在,如果您传递ifstream reference ptr代替FILE *ptr,则会出现编译错误。

因此,在这种情况下,您不能使用ifstream引用,但仍然可以使用 FILE 指针实现它,这也是C++中允许的。

extern "C"{
  //hear header file of your function ‘fread’ 
   #include <fread function headerfile.h>
}