gpt4 book ai didi

c++ - 从文件中读取 2 个字符串

转载 作者:太空宇宙 更新时间:2023-11-04 13:58:02 24 4
gpt4 key购买 nike

我需要从 C++ 文件中读取 2 个字符串(单词),虽然我的代码在运行程序时没有任何错误,但我收到以下消息:“strmatch.exe 已停止工作”。我怎样才能摆脱这个问题?

这是输入文件和我的代码:

// strmatch.in file
ABA
CABBCABABAB

// code
#include <iostream>
#include <fstream>
#include <string.h>

using namespace std;

#define length 2000001

int main() {
int i;
char a[length], b[length];
ifstream f("strmatch.in");
f>>a;
f>>b;
f.close();
for (i=0;i<strlen(a);i++)
cout<<a[i];
cout<<"\n";
for (i=0;i<strlen(a);i++)
cout<<b[i];
return 0;
}

最佳答案

此程序可能停止工作的原因有两个:

  • 您尝试分配的字符串对于您系统中的自动存储区(也称为“堆栈”)来说太大,或者
  • 您打开的文件不存在。

考虑为字符串使用 std::string 而不是 char 数组。这在内存方面更经济,并且可以保证您不会出现内存不足的错误。

如果您的作业需要使用如此长的 C 字符串,请考虑将字符串移动到动态内存中,如下所示:

char *a = new char[length];
char *b = new char[length];
// Do the work, then delete the char arrays
...
delete[] a;
delete[] b;

关于c++ - 从文件中读取 2 个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20556542/

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