0

I have written the program which fills an array of structures and then writes that array to txt file. The problem is that my program terminates in unusual way on windows vista command prompt line but dev-C++ shows no errors when compiles. I think that is related with the number of elements in the array but still can’t fix it in two days that. I will be very thankful for any ideas...

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

struct card {
       char name[40];
       char surname[40];     
};

card A = {"Anna", "Karenina"};

   
int main() {
    char answer;
    
    int i;
    card *arr = new card[i];
    
    
    int k = 0;
    
    do
    {
    k = k + 1;
    char word1 [40];
    char word2 [40];

    cout << "Enter a name..." << endl;
    cin >> word1;

    cout << "Enter a surname..." << endl;
    cin >>word2;


    strcpy (A.name, word1);
    strcpy (A.surname, word2);

    arr[k-1] = A;

       do {
        cout << "Would you like to enter next person? (Y/N)" << endl;
        cin >> answer;
        answer = toupper(answer);
        }
    while ((answer != 'Y') && (answer != 'N'));
    }
    while ( answer == 'Y');
    
    
    cout << "\nTHE ELEMENTS OF ARRAY" << endl;
    
    ofstream file ("cards.txt", ios::binary);
    if (!file)
    cerr << "Unable to open cards.txt" << endl;
    
    for (int x = 0; x < k; x++) {
    file.write((char *) &arr[x], sizeof(card));
    cout << x + 1 << " " << arr[x].name << " " << arr[x].surname << endl;
    }
    
    file.close();
    
    delete[] arr;
    
    return 0;
}

Edited by infogirl: the code is inserted not properly

2
Contributors
1
Reply
2
Views
5 Years
Discussion Span
Last Post by triumphost
1

Stop using Dev-C++ it is out of date.. Download Codeblocks and Mingw.. Your code is fine. I've compiled and ran the program and it terminates with 0.. No segfaults or crashes or anything. Also include the header for strcpy as it was undeclared.. Windows.h fixed that for me.

Time to upgrade ;)

Edited by triumphost: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.