【问题标题】:Read file contents, store in array, add more contents to the array, then store the new array in a file C++读取文件内容,存储在数组中,向数组添加更多内容,然后将新数组存储在文件中 C++
【发布时间】:2014-12-27 20:10:43
【问题描述】:

我有以下文件(customers.txt):

 1  esra    doha    017987  
 2  abdulla wakra   023456

问题:从用户那里获取新的客户信息并将其存储在文件中,而不删除旧记录。

我需要读取之前的内容并将它们存储在相应的数组中,我使用了这种方法:

void readFile()
{
ifstream infile;
infile.open("D:\\customers.txt");

for(int i = 0; infile; i++)
{
    infile >> ID[i] >> names[i] >> addresses[i]>>tn[i];
    infile.peek();
    numC++;
}

infile.close();
}

(numC为客户数量,初始设置为0)

然后,我需要添加一个新客户。我是这样做的:

void add()
{
for(int i=numC; i<100;i++)
{
    cout<<"Enter your ID (or -1 to quit)"<<endl;
    cin>>ID[i];
    if(ID[i]!=-1)
    {
        cout<<"enter your name"<<endl;
        cin>>names[i];
        cout<<"enter your address"<<endl;
        cin>>addresses[i];
        cout<<"enter your telephone number"<<endl;
        cin>>tn[i];
    }
    else
        break;
}
saveFile();
}

saveFile() 用于在添加新用户后将数组存储在文件中。这里是:

 void saveFile()
 {
ofstream outfile;
outfile.open("D:\\customers.txt");

for(int i=0; i<numC; i++)
    outfile << ID[i] << "\t" << names[i]<< "\t"<<addresses[i]<< "\t"<<tn[i]<<endl;

outfile.close();
}

我不确定问题出在哪里,在 add() 或 save() 中,但是,运行程序后,这些是内容:

 1  esra    doha    017987  
 2  abdulla wakra   023456
 0  0       0       0

为什么会这样?如何修复它以存储用户?

【问题讨论】:

    标签: c++ string file save add


    【解决方案1】:

    每次在 add() 例程中添加用户时,numC 都需要递增。

    此外,您可能会在新文件的末尾得到零,因为您的原始文件在第二行之后有一个返回行,因此您的读取函数尝试读取第三行,即使它是空白的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-23
      • 1970-01-01
      • 2021-11-11
      • 1970-01-01
      • 2021-07-06
      相关资源
      最近更新 更多