【发布时间】:2019-04-16 08:42:33
【问题描述】:
我一直在做一个实现散列的任务。在其中,我通读了一个名为“蛋白质”的文本文件。当我尝试将其复制到另一个 char 数组时会出现问题。 Visual Studio 引发读取访问冲突。
#include <iostream>
#include <fstream>
using namespace std;
struct arrayelement {
char protein[30];
int count;
};
arrayelement proteins[40];
int main()
{
char buffer[30];
// open source file
ifstream fin("proteins.txt");
if (!fin) { cerr << "Input file could not be opened\n"; exit(1); }
// loop through strings in file
while (fin >> buffer) {
int index = ((buffer[0] - 65) + (2 * (buffer[strlen(buffer)-1] - 65)) % 40);
while (true)
{
if (proteins[index].protein == buffer) // Found
{
proteins[index].count++;
break;
}
if (proteins[index].protein[0] == 0) // Empty
{
strcpy(proteins[index].protein, buffer); // <-- The error in question
proteins[index].count++;
break;
}
index++; // Collision
}
}
// close file
fin.close();
for (int i = 0; i <= 40; i++)
{
cout << proteins[i].protein << "\t" << proteins[i].count << "\n";
}
}
【问题讨论】:
-
你试过调试这个吗?发生错误时,索引可能为 40。
-
也可以使用
std::string和std::vector<arrayelement>。 -
proteins[index].protein == buffer这不是您想要比较 char 数组的方式。 -
@0x5453 天哪,我太累了。做到了。将其更改为 strcmp 后,它全部运行。谢谢!
-
@Noctimor 因为您在使用 C++ 时尝试使用 C。使用容器....
标签: c++ arrays file char strcpy