简体   繁体   中英

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". 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:

  • The strings that you are trying to allocate are too big for the automatic storage area (also known as "the stack") in your system, or
  • The file that you are opening does not exist.

Consider using std::string instead of char arrays for your strings. 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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