C++ 尝试从文件缓冲区复制到字符数组时发生读取访问冲突

C++ 尝试从文件缓冲区复制到字符数组时发生读取访问冲突,c++,arrays,file,char,strcpy,C++,Arrays,File,Char,Strcpy,我一直在做一个任务来实现哈希。在里面,我读了一个叫做“蛋白质”的文本文件。当我试图将它复制到另一个字符数组时,问题就出现了。Visual Studio引发读取访问冲突 #include <iostream> #include <fstream> using namespace std; struct arrayelement { char protein[30]; int count; }; arrayelement proteins[40]; int main

我一直在做一个任务来实现哈希。在里面,我读了一个叫做“蛋白质”的文本文件。当我试图将它复制到另一个字符数组时,问题就出现了。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";
  }
}
#包括
#包括
使用名称空间std;
结构阵列{
炭蛋白[30];
整数计数;
}; 
排列蛋白[40];
int main()
{
字符缓冲区[30];
//开源文件
ifstream-fin(“proteins.txt”);
如果(!fin){cerr>缓冲区){
int索引=((缓冲区[0]-65)+(2*(缓冲区[strlen(缓冲区)-1]-65))%40);
while(true)
{
if(proteins[index].protein==buffer)//已找到
{
蛋白质[索引]。计数++;
打破
}
if(proteins[index].protein[0]==0)//空
{

strcpy(蛋白质[索引]。蛋白质,缓冲液);//如果你在这里得到超过30个字符:

while (fin >> buffer) {
…或者如果此处的索引>=40:

strcpy(proteins[index].protein, buffer);
…程序可能会崩溃(未定义的行为)。此外,这些
char*
将不会指向同一地址,因此比较将失败:

proteins[index].protein == buffer

你试过调试这个吗?发生错误时索引可能在40。也可以使用
std::string
std::vector
蛋白质[index]“蛋白质==缓冲区< /代码>这不是你想比较的字符数组。哦,老兄,我太累了。这就行了。在把它变成一个STRCMP之后,它都运行了。谢谢!”NoCimor,因为你在C++的时候尝试做C。使用容器……是的,是我做的比较。重写后,一切都运行。这里的de是根据作业给出的——我们正在使用的示例保证不超过30,并且给出的索引是所需的两倍,以练习冲突解决。否则我也绝对会清理这些内容。谢谢!太好了!注意:如果输入字符串是
“z”,则索引公式将得到91
。它将变成:
index=57+114%40
=>
57+(114%40)