我正在尝试使用 ifstream 将此 C 函数的等效代码执行到 c++ 中
I am trying to do the equivalent code of this C function into c++ with ifstream
此函数读取一个包含字符大小数字的文本文件(文本文件在另一个程序中以字符编写),我需要在读取后将它们转换为整数。由于我的程序的其余部分都在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>
}
- 以下代码执行哪种内存分配(动态或静态)?
- 允许多个互斥锁所有者或指定数量的并发代码执行
- 使用 execv 从C++代码执行的 Linux 脚本失败
- 由于找不到cpprest_2_10.dll,代码执行无法继续
- 在每次循环迭代时停止代码执行毫秒
- 与Java相比,为什么此C 代码执行速度如此慢
- 记录组件代码执行
- 相同的代码执行两次:性能差异
- 代码执行/CPU 速度每 2 秒减慢一次
- 函数返回本地变量,尽管变量不超出范围,没有编译器问题,并且代码执行
- 如何将字符串从C++DLL返回到MetaTrader 4代码执行生态系统?
- 当我从java代码执行C++时不显示任何输出
- C++和共享库中的代码执行点
- 递归期间代码执行中断
- 为可选的评测代码执行进行高效设计
- 我正在尝试使用 ifstream 将此 C 函数的等效代码执行到 c++ 中
- 最佳C 11测量嵌入式系统代码执行时间的方法
- 如何在iOS应用程序中锁定代码执行
- 中断代码执行
- 是否有一个工具来记录代码执行