當我運行我的代碼時,下面的向量具有存儲在其中的正確數據,但由於某些原因,它沒有正確寫入硬編碼文件路徑,而是保留了txt文件空白。我相信這是我忽略的一些簡單的東西。在C++ ofstream和vector中寫入空白文件
已更新:這裏是更完整的的代碼。
// Declare the necessary include(s)
#include <iostream>
#include <vector>
#include "Account.h"
/* main function
Purpose: To test the creation of two classes & make sure they output correctly
Parameters: None
Returns: an int (0) */
int main()
{
// Declare local variable
int i = 0;
// Create a vector of Account objects.
vector <Random> randomVector;
// Create three person objects.
Person bob("billy bob", "bobsway");
Person joe("joe joe", "cityofjoe");
Person george("george jack", "georgetown");
// Create three Account objects, where each account object contains a Person object.
Account bobby(bob, 1, 500);
Account joseph(joe, 2, 1000);
Account george(george, 3, 1200);
// Push these Account objects into the vector.
randomVector.push_back(bobby);
randomVector.push_back(joseph);
randomVector.push_back(george);
// Create an ofstream object
ofstream oDataAccount("accountData.txt");
// Create a loop to write Account data to a file
for (i = 0; i < randomVector.size(); i++)
{
// Flush the output file
oDataAccount.flush();
// Write the data from each object in the vector
randomVector[i].writeData(oDataAccount);
}
// Close the file.
oDataAccount.close();
// Keep the console window open with PAUSE
system("PAUSE");
// Return a 0
return 0;
}// End main
賬戶類
// Include pragma once
#pragma once
#include "Person.h"
class Account
{
private:
Person aPerson;
int accountNum;
double accountBalance;
public:
Account();
Account(const Person, int, double);
Person getPerson();
int getAccountNum();
double getAccountBalance();
// writeData function
void writeData(ofstream&);
};
// Include the Account header file
#include "Account.h"
Account::Account()
{
// Initializes data members
}
Account::Account(const Person p, int accNum, double accBal)
{
aPerson = p;
accountNum = accNum;
accountBalance = accBal;
}
Person Account::getPerson()
{
return aPerson;
}
int Account::getAccountNum()
{
return accountNum;
}
double Account::getAccountBalance()
{
return accountBalance;
}
// Implementation for writeData function
void Account::writeData(ofstream& output)
{
// Write class data to the file
output << getPerson().getName() << ' ' << getPerson().getAddress() << ' ' << getAccountNum() << ' ' << getAccountBalance();
}
Person類
#pragma once
#include <string>
#include <fstream>
using namespace std;
class Person
{
private:
string name;
string address;
public:
Person();
Person(const string, const string);
string getName();
string getAddress();
};
#include "Person.h"
Person::Person()
{
}
Person::Person(const string n, const string a)
{
name = n;
address = a;
}
string Person::getName()
{
// Return the name
return name;
}
string Person::getAddress()
{
// Return the address
return address;
}
FYI'ofstream oDataFile(「randomData.txt」);'已經打開文件,你不需要明確地打開' – CoryKramer
你的向量可以是空的。發佈完整的可編譯示例。 –
我想添加一個randomVector.size()不是0的檢查;如果是,則該文件將爲空白。這將有助於有一個完整的例子(我很欣賞這可能是不可能的)。 –