[英]Reading 2 strings from file
I need to read 2 strings (words) from a file in C++ and although my code doesn't have any errors when I run the programme I get the following message: "strmatch.exe has stopped working". 我需要从C ++文件中读取2个字符串(单词),尽管运行程序时我的代码没有任何错误,但我收到以下消息:“ strmatch.exe已停止工作”。 How can I get rid of this problem?
我如何摆脱这个问题?
Here is the input file and my code: 这是输入文件和我的代码:
// 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;
}
There are two reasons why this program may stop working: 该程序可能会停止工作的原因有两个:
Consider using std::string
instead of char
arrays for your strings. 考虑为
std::string
使用std::string
而不是char
数组。 This is more economical in terms of memory, and it guarantees you against insufficient memory errors. 就内存而言,这是更经济的方法,它可以确保您不会遇到内存不足的错误。
If using C strings of such enormous length is required by your assignment, consider moving the strings to dynamic memory, like this: 如果您的分配要求使用如此长的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.