gpt4 book ai didi

c++ - 如何修复 C++ 中结构的段错误?

转载 作者:行者123 更新时间:2023-11-27 23:40:05 24 4
gpt4 key购买 nike

我正在尝试将文本文件中的每个唯一单词写入一个唯一单词结构我还没有那么远,但是在尝试将值写入我的结构数组时出现段错误。

我们不能使用指针,因为我们还没有了解它们,我们必须使用 using namespace std。

我很好地弄清楚如何对唯一单词部分使用循环,我只需要帮助弄清楚如何修复段错误。我已将范围缩小到段错误从 do-while 循环中的 for 循环开始的位置,但我不知道从那里去哪里,而且我在网上找不到任何帮助。

#include <iostream>
#include <fstream>
#include <cmath>
#include <string>

using namespace std;

struct UniqueWord{
string word;
int numOccurences;
};

int main(){

const int N = 100000;
ifstream CleanedText;
CleanedText.open("testTextCleaned.txt"); //change to proper text later
string word1;
string words[N];
for(int i = 0; i < N; i++){
CleanedText >> words[i];
}
CleanedText.close();
CleanedText.open("testTextCleaned.txt"); //change to proper text later
UniqueWord wordarray[N];
for(int i = 0; i < N; i++){
CleanedText >> word1;
do{
for(int j = 0;j<N+1;j++){
wordarray[j].word = word1;
}
}while(words[i] != word1);

}

return 0;
}

我希望能够将原始文件中的每个单词放入结构数组中。

最佳答案

在结束条件上丢失 +1

        for(int j = 0;j<N/*+1*/;j++){
wordarray[j].word = word1;
}

J 需要从 0 到 N-1。假设 N 为 2,则 wordarray[0] 和 wordarray[1] 有效。 wordarray[2] 不是。

关于c++ - 如何修复 C++ 中结构的段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55869751/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com