使用 std::fgetc() return 分配数组

Assigning an array with std::fgetc() return

我正在尝试使用 std::fgetc 函数

存储 .awv 文件的第一个 4 char

这就是我的

FILE* WAVF = fopen(FName, "rb");
std::vector<std::string> ID;
ID[4];
for (int i = 0; i < 4; i++)
{
    ID[i] = fgetc(WAVF);
}

我不断收到此错误:

Exception thrown at 0x00007FF696431309 in ConsoleApplication3.exe: 
0xC0000005: Access violation writing location 0x0000000000000010.

您的程序有 undefined behavior!

您的矢量 ID 是空的。通过在空 std::vector 上调用 operator[],调用 undefined behavior。您很幸运,您的程序崩溃了,提示“访问冲突”。

您需要:

// create a vector of string and initialize 4 empty strings
std::vector<std::string> ID(4); 

for (auto& element: ID)
{
    element = some `std::string`s
}

但是,在你的情况下,std::fgetc returns int

The obtained character on success or EOF on failure.

因此您可能需要 std::vector<char> 或(最多)std::string.

等数据结构