【问题标题】:C++ Saving 2-dimensional database into file ISSUEC++ 将二维数据库保存到文件 ISSUE
【发布时间】:2017-05-16 09:29:05
【问题描述】:

我正在编写一个小型控制台应用程序(将其命名为学生证据),它有几个功能,即它允许用户将数据库导出到文本文件中。

在这个过程中出现的问题是程序实际上只保存了提到的数据库的第一条记录。

void saveDataToFile() {             // ZAPISZ BAZĘ DANYCH DO PLIKU - ISTNIEJE PROBLEM Z OKREŚLENIEM ŚCIEŻKI ZAPISU ORAZ ZAPISYWANIEM JEDYNIE PIERWSZEGO REKORDU Z BAZY
string fileName;
ofstream fileTemp;
cout << "Podaj nazwę pliku: "; cin >> fileName;
fileTemp.open(fileName);
fileTemp << "+--------------------------------------------------------------------------------------------------------+" << endl;
fileTemp << "|\tImię\t|\tNazwisko\t|\tNr PESEL\t|\t Telefon\t|\tMail\t |" << endl << "+--------------------------------------------------------------------------------------------------------+" << endl;
for (row; row < 20; row++) {
    for (col; col < 5; col++) {
        if (col == 0) {
            fileTemp << "\t" << studentDb[row][col] << "\t";
        }
        else {
            fileTemp << studentDb[row][col] << "\t";
        }
    }
    fileTemp << endl;
}
fileTemp.close();

}

我不知道该代码有什么问题,因为循环本身似乎完全没问题...

我很乐意提供解决此问题的任何提示。 忽略用波兰语编写的行 - 它在程序中只有一些装饰性的文本格式功能。

编辑。

我创建新记录的方式:

void createNewRecord() {        // UTWÓRZ NOWY REKORD W BAZIE
string *pNewRecord;
pNewRecord = &studentDb[recordCounter][0];
cout << "Imię: "; cin >> *pNewRecord;
pNewRecord = &studentDb[recordCounter][1];
cout << "Nazwisko: "; cin >> *pNewRecord;
pNewRecord = &studentDb[recordCounter][2];
cout << "Numer PESEL: "; cin >> *pNewRecord;
pNewRecord = &studentDb[recordCounter][3];
cout << "Numer telefonu: "; cin >> *pNewRecord;
pNewRecord = &studentDb[recordCounter][4];
cout << "Adres e-mail: "; cin >> *pNewRecord;
recordCounter++;
cout << endl << "Nowy rekord został pomyślnie dodany do bazy." << endl;
cout << "Czy chcesz kontynuować? (t/n): "; cin >> response;
cout << endl;
if (response == 't' || response == 'T') {
    cout << "Kontynuujesz dodawanie do bazy." << endl << endl;
    createNewRecord();
}
else if (response == 'n' || response == 'N') {
    Sleep(1000);
    system("cls");
    void displayMenuWindow();
}

}

【问题讨论】:

  • rowcol 是班级成员吗?为什么不使用局部变量作为循环索引?
  • 您是否在调试器中单步执行了循环?
  • 是否有可能您确实写了所有记录,但它们都在一行中,因为您没有在每条记录后插入换行符?
  • col & row 是全局定义的变量,我在程序中的多个嵌套数组操作循环中使用它们。调试器不会返回任何可见的问题或错误。
  • 我认为使用全局循环索引是自找麻烦。

标签: c++ arrays file save


【解决方案1】:

在“for”循环的初始化部分将“row”和“col”变量设置为零。并将它们也设为局部变量(将它们声明为“int row=0”)。

【讨论】:

  • 是的,成功了!非常感谢,我撤回了我之前关于这些该死的变量的所有言论。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多