繁体   English   中英

从文件中读取2个字符串

[英]Reading 2 strings from file

我需要从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使用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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM