如何将特定的结构从数组写入new.txt文件,仅此而已? [英] How to write the particular structures from array to new.txt file and nothing more?

查看:54
本文介绍了如何将特定的结构从数组写入new.txt文件,仅此而已?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,伙计们.

首先,我程序的函数fillCards将名称和姓氏保存在结构中,然后将其写入cards.txt文件.然后,功能readCard将结构读取到数组中并显示它们.当用户输入结构编号时,该函数将数组的结构(编号与用户输入的编号相同的结构除外)写入new.txt文件.问题在于,new.txt文件中填充了与cards.txt相同数量的结构,并且重复写入了最后一个结构,而不是被忽略的结构.如何将特定的结构从数组写入new.txt文件,仅此而已?我将非常感谢您的帮助.

Hello, guys.

Firstly, my program’s function fillCards saves a name and a surname in the structure and then writes it to cards.txt file. Then the function readCard reads structures to the array and show them. When user enters the number of structure, the function writes the structures of the array (except the structure which number is the same as the user’s entered number) to new.txt file. The problem is that new.txt file is filled with the same number of structures as cards.txt and instead of ignored structures the last structure is repeatedly written. How to write the particular structures from array to new.txt file and nothing more? I will be very greatful for any help.

#include <iostream>
#include <fstream>
#include <string>
#include <cstring>

using namespace std;

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

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

int fillCards() {

    //cards.txt is filled with stuctures
    char answer;
    int i = 0;

    ofstream file ("cards.txt", ios::binary);
    if (!file)
    cerr << "Unable to open cards.txt" << endl;

    do
    {
    i++;
    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);

    file.write((char *) &A, sizeof(card));

    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');

    file.close();

    return 0;
}


int readCards() {

    int i, k, length;


    //Structures are read to array from card.txt file

    ifstream file ("cards.txt", ios::binary);

    if (!file)
    cerr << "Unable to open cards.txt" << endl;

    file.seekg (0, ios::end);
    length = file.tellg();
    file.seekg (0, ios::beg);

    i = length/sizeof(card);

    card *arr = new card[i];

    for (int n = 0; n < i; n++) {
    file.read((char *) &S, sizeof(card));
    arr[n] = S;
    cout << (n+1) << " " << arr[n].name << " " << arr[n].surname << endl;
    }

    file.close();

    //Structures are written to new.txt file
    _unlink("cards.txt");
    
    ofstream rubber ("new.txt", ios::binary);

    if (!rubber)
    cerr << "Unable to open new.txt" << endl;

    cout << "Enter a number of person which you want to delete" << endl;
    cin >> k;

    for (int x = 0; x < i; x++) {
    if ((x + 1) != k ){
                rubber.write((char *) &arr[x], sizeof(card));
                cout << (x + 1) << " " << arr[x].name << " " << arr[x].surname << endl;
                    }
    }

    rubber.close();

    delete[] arr;

    return 0;
}


int showCards () {

    //Read new.txt file and show it to the user

    cout << "\nNaujas turinys" << endl;

    int m = 0;
    ifstream file ("new.txt", ios::binary);

    if (!file)
    cerr << "Unable to open new.txt" << endl;

    while((!file.eof()) && (!file.fail())) {
    m = m + 1;
    file.read((char *) &S, sizeof(card));
    cout << m << " " << S.name << " " << S.surname << endl;
    }

    file.close();
    return 0;
}

int main() {

    fillCards();
    readCards();
    showCards();

    return 0;
}



我已经纠正了动态数组元素个数的错误.但是我的问题仍然存在.
例如cards.txt的内容:
1夏洛特·史密斯
2艾玛·琼斯
3索菲亚·贝克
4 Bernadette Soubirous

然后,我选择数字2(k的值),然后程序将数组元素(带有Emma Jones的元素)写入new.txt. new.txt的内容如下所示:
1夏洛特·史密斯
2索菲亚·贝克
3 Bernadette Soubirous
4 Bernadette Soubirous

但是我需要new.txt的内容像这样:
1夏洛特·史密斯
2索菲亚·贝克
3 Bernadette Soubirous

有什么想法吗?



I''ve corrected mistake of number of the dynamic array''s elements. But still my problem exists.
For example the contents of cards.txt :
1 Charlotte Smith
2 Emma Jones
3 Sophia Baker
4 Bernadette Soubirous

Then I choose number 2 (the value of k) and then program writes elements of array to new.txt except the element with Emma Jones. The contents of new.txt look like this:
1 Charlotte Smith
2 Sophia Baker
3 Bernadette Soubirous
4 Bernadette Soubirous

But I need the contents of new.txt to be like this:
1 Charlotte Smith
2 Sophia Baker
3 Bernadette Soubirous

Any ideas?

推荐答案

另一个可能不是您问题根源的bug,但应予以注意:
Another bug that is probably not the source of your problem but should be noted:
int i, m = 0, n, k;
card *arr = new card[i];


这会分配一个随机大小的数组,因为i尚未初始化.您的编译器应生成一条警告消息.如果不是,请提高编译器警告级别.

您可以使用文件大小除以结构大小来获得存储在文件中的结构数,并将其用作数组大小.


This allocates an array of random size, because i is not initialized. Your compiler should generate a warning message. If not, increase the compiler warning level.

You may use the file size divided by the structure size to get the number of structures stored in the file and use this as array size.


我之前说过,我会说再次-代码中的文件读取循环无法按预期工作..

我建议您复制之前提供的文件读取循环,并用它替换ShowCards中的循环.

另外,您是否考虑过当输入用户名并读入S.name和S.surname时,您不会清除这些数组中的任何旧数据.这会导致将错误的数据同时写入cards.txt和new.txt

考虑输入的两个名称:
名称:彼得"
姓:"Fitzgibbon"

现在,考虑下一次在循环中输入以下名称:
姓名:娄"
surName:"Pan"

您的姓名/姓氏数组现在将保留:

"Lou \ 0r"
"Pan \ 0gibbon"

如果您打印此文本,虽然看不到"r"或长臂猿",但请使用十六进制编辑器查看该文件,然后在其中看到多余的文本.

解决方案?在将数据存储到阵列之前,请先清除它们.在准备读取数据之前,先将内存集A.name和A.surname

当您更改循环并修复未初始化的数据时,您的程序就可以正常工作. :)
I said it earlier and I''ll say it again - the file-reading loops in your code don''t work as expected..

I suggest you copy the file-reading loop I provided earlier and replace the one in ShowCards with it.

Also, have you considered that when a user name is entered and read into S.name and S.surname, that you''re not clearing out any old data in these arrays. This causes erroneous data to be written to both cards.txt and new.txt

Consider these two names entered:
name: "Peter"
surName: "Fitzgibbon"

Now, consider that the next time through the loop, this name is entered:
name: "Lou"
surName: "Pan"

Your name/surname arrays will now hold:

"Lou\0r"
"Pan\0gibbon"

While you won''t see the ''r'' or the ''gibbon'' if you print this text, take a look at the file with a hex-editor and you''ll see the extra text there.

The solution? Clear the arrays before you store data to them. Just before you strcpy the read data, memset A.name and A.surname

When you change the loop and fix the uninitialized data, your program works just fine. :)


该行
while((!file.eof()) || (!file.fail())) {



应该是



Should probably be

while((!file.eof()) && (!file.fail())) {



您应该使用调试器逐步执行程序,并查看变量和测试是否按照预期的方式执行.



You should step through your program with the debugger and see if the variables and tests are doing what you expect them to do.


这篇关于如何将特定的结构从数组写入new.txt文件,仅此而已?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆