将数据存储到数组中的问题

时间:2012-10-24 12:26:29

标签: c++ arrays fstream

我的程序允许用户在输入用户名时删除指定的记录。当它们传入名称时,它将调用一个方法将它们存储到一个数组中,并将它们写回文件而不附加,以便重新写入该文件。 但是在存储部分存在一些问题,我的文本文件的最后一行没有正确存储,而是从第二行复制并复制到包含名称的最后一行。 希望no1会混淆:/。存储在我的数组中的文本文件和数据的示例在下面,我使用粗体和斜体来表示更清晰的图片,以及deleteRec的方法。

这是我的文本文件所包含的内容。

user;pass;1234;John;1111
user1;pass1;2345;May;2222
user2;pass2;3456;Mary;3333
user3;pass3;4567;Andy;4444
hr;hr;5678;Jonathan;5555
admin;admin;6789;Aili;6666
user10;pass10;7890;eggy;9999
user11;pass11;9807;Mary;7777

当我运行要删除的程序时,这是我的输出。

Data stored in store[] array: user1;pass1;2345;May;2222
Data stored in store[] array: user2;pass2;3456;Mary;3333
Data stored in store[] array: user3;pass3;4567;Andy;4444
Data stored in store[] array: hr;hr;5678;Jonathan;5555
Data stored in store[] array: admin;admin;6789;Aili;6666
Data stored in store[] array: user10;pass10;7890;eggy;9999
***Data stored in store[] array: ;pass10;7890;eggy;9999***
Data stored in store[] array: 


bool Employee::deleteRec(string nm)
{
    int count;
    int i=0;//for looping
    ifstream file("login1.txt");
    string fusername,empty;
    string store[100];//initialize a array to store textfile contents
    while (!file.fail()) 
    {       
        getline(file,fusername,';');// use ; as delimiter
        getline(file,empty);// use line end as delimiter, and to skip the rest of the information
        string add="";//initialize add string to nothing when it loops
        add += fusername+';'+empty; //adds back the username and rest of the line together back
        if(fusername!=nm)//to check if the username in textfile do not match the user input name
        {
            store[i]=add; //store into an array
            cout<<"i is: "<<i<<endl;
            cout<<"store array[] = "<<store[i]<<endl;
            i++;
        }
        else{}
    }

    //ofstream pwd2_file ("login1.txt", ios::app); //suppose to user this if im writing to file

    for(int x=0;x<i+1;x++)
    {
        cout<<"Data stored in store[] array: "<<store[x]<<endl;
    }

    return false;
}

2 个答案:

答案 0 :(得分:1)

循环的问题在于,当您到达文件末尾时,您的流也不会失败。它只在下次读取时失败,但您没有验证这一点。

因此,您的数组包含两次最后一条记录。

你有一个空字符串作为第一个字段可能是因为它将此字段设置为空以读入它(流尚未处于失败状态)或因为输入结束时有一个空行读入的文件。

为您的用户及其数据创建一个结构,并从流中读入。如果整个读取成功,则可以附加到数据集。

我建议你使用std::vectorpush_back()

循环的正确方法如下:

struct EmployeeData
{
    std::string name;
    // fill in members
;

std::istream& operator>>( std::istream& is, EmployeeData& emp )
{
     std::getline( is, emp.name(), ';' );
     // etc.

     return is;
}

std::vector< EmployeeData > emps;
EmployeeData emp;
while( is >> emp )
{ 
   emps.push_back( emp );
}

答案 1 :(得分:0)

我建议使用调试器并找出传递的内容。看起来像输出存储在数组中的一个错误,或者当它被重写到文件时。可以解释你缺乏边界用户。