首页 > 解决方案 > 我输入的任何数组大小超过 36603 时都会返回“堆栈溢出”错误。如何使字符串能够捕获整个 .txt 文件?

问题描述

我需要创建一个能够容纳大约 100500 个单词的整本书“饥饿游戏”的字符串。我的代码可以捕获 txt 的样本,但是每当我超过 36603(已测试)的字符串大小时,我都会收到“堆栈溢出”错误。

我可以成功捕获低于 36603 个元素的任何东西,并且可以完美地输出它们。

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

using namespace std;

int main() 
{
    int i;
    char set[100];
    string fullFile[100000]; // this will not execute if set to over 36603

    ifstream myfile("HungerGames.txt");
    if (myfile.is_open())
    {
        // saves 'i limiter' words from the .txt to fullFile
        for (i = 0; i < 100000; i++) {
            //each word is saparated by a space
            myfile.getline(set, 100, ' ');
            fullFile[i] = set;
        }
        myfile.close();
    }
    else cout << "Unable to open file";

    //prints 'i limiter' words to window
    for (i = 0; i < 100000; ++i) {
        cout << fullFile[i] << ' ';
    }

是什么导致“堆栈溢出”,如何成功捕获 txt?我稍后会做一个单词计数器和单词频率计数器,所以我需要“每个元素的单词”形式。

标签: c++

解决方案


函数中使用多少堆栈是有限制的;改用std::vector

更多herehere。Visual Studio 中的默认值是 1MB(更多信息在这里),您可以使用 /F 更改它,但这通常是个坏主意。


推荐阅读