C++ 为什么赢了';当我把它放在我的while语句之外时,它不是我的流工作吗?

C++ 为什么赢了';当我把它放在我的while语句之外时,它不是我的流工作吗?,c++,serialization,file-io,fstream,C++,Serialization,File Io,Fstream,每次我做任何事情,在我的主函数中调用我的while(1),我的文件就会被清除。这快把我逼疯了。我什么都试过了。我试图把我的数据流(“data.dat”);在while(1)语句之外,所以它不是每次都被调用,但是没有任何东西被写入文件,就像ofstream不工作一样 我已尝试使ofstream保持静态,因此它不会被反复调用,如: static ofstream open("data.dat"); 那不行 就像我说的,当我把ofstream放在while语句之外时,没有任何内容写入文件。比如: o

每次我做任何事情,在我的主函数中调用我的while(1),我的文件就会被清除。这快把我逼疯了。我什么都试过了。我试图把我的数据流(“data.dat”);在while(1)语句之外,所以它不是每次都被调用,但是没有任何东西被写入文件,就像ofstream不工作一样

我已尝试使ofstream保持静态,因此它不会被反复调用,如:

static ofstream open("data.dat");
那不行

就像我说的,当我把ofstream放在while语句之外时,没有任何内容写入文件。比如:

ofstream out("data.dat");

    while (1)
    {


        string line = "";
        cout << "There are currently " << structList.size() << " items in memory.";
        cout << endl << endl;
        cout << "Commands: " << endl;
        cout << "1: Add a new record " << endl;
        cout << "2: Display a record " << endl;
        cout << "3: Edit a current record " << endl;
        cout << "4: Delete a record " << endl;
        cout << "5: Save current information " << endl;
        cout << "6: Exit the program " << endl;
        cout << endl;
        cout << "Enter a command 1-6: ";

        getline(cin , line);

        int rValue = atoi(line.c_str());

        system("cls");

        switch (rValue)
        {
            case 1:
                structList = addItem(structList);
                break;
            case 2:
                displayRecord(structList);
                break;
            case 3:
                structList = editRecord(structList);
                break;
            case 4:
                deleteRecord(structList);
                break;
            case 5:
                if (!structList.size()) { cout << "There are no items to save! Enter one first!" << endl << endl; system("pause"); system("cls"); break; }
                writeVector(out , structList);
                break;
            case 6:
                return 0;
            default:
                cout << "Command invalid. You can only enter a command number 1 - 6. Try again. " << endl;
        }

        out.close();
    }
我对我的程序一次又一次地在启动时崩溃感到恶心和厌倦,因为我的向量设置为2亿的大小。我已经试过很多东西了。。。都不管用。。。上帝啊,有人帮我做这两件事!我已经为此工作了18个小时(是的,一整晚),我几乎完成了。我求你了

我的代码:

bool checkFileEmpty()
{
    ifstream in("data.dat");

    if (in.peek() == in.eofbit)
    {
        return true;
    }

    return false;
}
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <vector>

using namespace System;
using namespace std;
#pragma hdrstop

bool isValidChoice(int size, int choice);

bool checkFileEmpty();

template<typename T>
void writeVector(ofstream &out, const vector<T> &vec);

template<typename T>
vector<T> readVector(ifstream &in);

template<typename T>
vector<T> addItem(vector<T> &vec);

template<typename T>
void printItemDescriptions(vector<T> &vec);

template<typename T>
int displayRecord(vector<T> &vec);

template<typename T>
vector<T> editRecord(vector<T> &vec);

template<typename T>
vector<T> deleteRecord(vector<T> &vec);


struct InventoryItem {
    string Description;
    int Quantity;
    int wholesaleCost;
    int retailCost;
    string dateAdded;
} ;


int main(void)
{
    cout << "Welcome to the Inventory Manager extreme! [Version 1.0]" << endl;
    ifstream in("data.dat");
    if (in.is_open()) { cout << "File \'data.dat\' has been opened successfully." << endl; } else { cout << "Error opening data.dat" << endl;}
    cout << "Loading data..." << endl;
    vector<InventoryItem> structList = readVector<InventoryItem>( in );
    cout <<"Load complete." << endl << endl;
    in.close();

    while (1)
    {


        string line = "";
        cout << "There are currently " << structList.size() << " items in memory.";
        cout << endl << endl;
        cout << "Commands: " << endl;
        cout << "1: Add a new record " << endl;
        cout << "2: Display a record " << endl;
        cout << "3: Edit a current record " << endl;
        cout << "4: Delete a record " << endl;
        cout << "5: Save current information " << endl;
        cout << "6: Exit the program " << endl;
        cout << endl;
        cout << "Enter a command 1-6: ";

        getline(cin , line);

        int rValue = atoi(line.c_str());

        system("cls");

        ofstream out("data.dat");

        switch (rValue)
        {
            case 1:
                structList = addItem(structList);
                break;
            case 2:
                displayRecord(structList);
                break;
            case 3:
                structList = editRecord(structList);
                break;
            case 4:
                deleteRecord(structList);
                break;
            case 5:
                if (!structList.size()) { cout << "There are no items to save! Enter one first!" << endl << endl; system("pause"); system("cls"); break; }
                writeVector(out , structList);
                break;
            case 6:
                return 0;
            default:
                cout << "Command invalid. You can only enter a command number 1 - 6. Try again. " << endl;
        }

        out.close();
    }

    system("pause");

    return 0;
}

template<typename T>
void writeVector(ofstream &out, const vector<T> &vec)
{
    out << vec.size();

    for(vector<T>::const_iterator i = vec.begin(); i != vec.end(); i++)
    {
        out << *i;
    }
    cout << "Save completed!" << endl << endl;
}

ostream &operator<<(ostream &out, const InventoryItem &i)
{
    out << i.Description << ' ';
    out << i.Quantity << ' ';
    out << i.wholesaleCost  << ' ' << i.retailCost  << ' ';
    out << i.dateAdded  << ' ';
    return out;
}


istream &operator>>(istream &in, InventoryItem &i)
{
    in >> i.Description;
    in >> i.Quantity;
    in >> i.wholesaleCost >> i.retailCost;
    in >> i.dateAdded;
    return in;
}



template<typename T>
vector<T> readVector(ifstream &in)
{

    size_t size;
    if (checkFileEmpty())
    {
        size = 0;
    } else {
        in >> size;
    }

    vector<T> vec;
    vec.reserve(size);

    for(unsigned int i = 0; i < size; i++)
    {
        T tmp;
        in >> tmp;
        vec.push_back(tmp);
    }

    return vec;
}

template<typename T>
vector<T> addItem(vector<T> &vec)
{
    system("cls");

    string word;
    unsigned int number;

    InventoryItem newItem;

    cout << "-Add a new item-" << endl << endl;
    cout << "Enter the description for the item: ";
    getline (cin , word);
    newItem.Description = word;

    cout << endl;
    cout << "Enter the quantity on hand for the item: ";
    getline (cin , word);
    number = atoi(word.c_str());
    newItem.Quantity = number;

    cout << endl;
    cout << "Enter the Retail Cost for the item: ";
    getline (cin , word);
    number = atoi(word.c_str());
    newItem.retailCost = number;

    cout << endl;
    cout << "Enter the Wholesale Cost for the item: ";
    getline (cin , word);
    number = atoi(word.c_str());
    newItem.wholesaleCost = number;

    cout << endl;
    cout << "Enter current date: ";
    getline (cin , word);
    newItem.dateAdded = word;

    vec.push_back(newItem);

    return vec;
}

template<typename T>
void printItemDescriptions(vector<T> &vec)
{
    int size = vec.size();

    if (size)
    {
        cout << "---------------------------------" << endl;
        cout << "|      ~ Item Descriptions ~    |" << endl;
        cout << "---------------------------------" << endl;
        cout << "*********************************" << endl;
        for (int i = 0 ; i < size ; i++)
        {
            cout << "(" << i+1 << ")" << ": " << vec[i].Description << endl;
        }
        cout << "*********************************" << endl << endl;
    }
}

template<typename T>
int displayRecord(vector<T> &vec)
{
    string word = "";
    string quit = "quit";
    int choice = 1;
    int size = vec.size();

    if (size)
    {
        printItemDescriptions(vec);
        cout << endl;

        while (1)
        {
            cout << "Type \"exit\" to return to the Main Menu." << endl << endl;
            cout << "Enter \"list\" to re-display the items." << endl << endl;
            cout << endl;
            cout << "Pick the number of the item you would like to display: ";
            getline (cin , word);

            if (convertToLower(word) == "exit") { system("cls"); return 0; }
            if (convertToLower(word) == "list") { system("cls"); displayRecord(vec); }

            choice = atoi(word.c_str());

            choice -= 1;

            if (isValidChoice(size, choice))
            {
                system("cls");
                cout << endl << "[Item (" << choice << ") details] " << endl << endl;
                cout << "******************" << endl;
                cout << "*  Description   * " << vec[choice].Description << endl;
                cout << "******************" << endl << endl;
                cout << "******************" << endl;
                cout << "*Quantity On Hand* " << vec[choice].Quantity << endl;
                cout << "******************" << endl << endl;
                cout << "******************" << endl;
                cout << "* Wholesale Cost * " << vec[choice].wholesaleCost << endl;
                cout << "****************** " << endl << endl;
                cout << "******************" << endl;
                cout << "*  Retail Cost   * " << vec[choice].retailCost << endl;
                cout << "****************** " << endl << endl;
                cout << "******************" << endl;
                cout << "*  Data Added    * " << vec[choice].dateAdded << endl;
                cout << "****************** " << endl << endl;
            } else { system("cls"); cout << "That item doesn't exist!" << endl; cout << "Pick another item or enter \"list\" to see available items." << endl << endl; }
        }
    } else { cout << "There are currently no items to display." << endl << endl; system("pause"); system("cls"); return 0; }

    return 1;
}

bool isValidChoice(int size, int choice)
{
    for (int i = 0 ; i <= size ; i++)
    {
        if (choice == i) { return true; }
    }
    return false;
}

string convertToLower(string word)
{
    for (unsigned int i = 0 ; i < word.size() ; i++)
    {
        word[i] = tolower(word[i]);
    }

    return word;
}

bool checkFileEmpty()
{
    ifstream in("data.dat");

    if (in.peek() == in.eofbit)
    {
        return true;
    }

    return false;
}

template<typename T>
vector<T> editRecord(vector<T> &vec)
{
    string word;
    int choice;
    printItemDescriptions(vec);

    cout << "Choose item to edit: ";
    getline ( cin, word );
    choice = atoi(word.c_str());


    system("cls");

    unsigned int number;

    InventoryItem newItem;

    cout << "-Edit an item-" << endl << endl;
    cout << "Enter the description for the item: ";
    getline (cin , word);
    vec[choice-1].Description = word;

    cout << endl;
    cout << "Enter the quantity on hand for the item: ";
    getline (cin , word);
    number = atoi(word.c_str());
    vec[choice-1].Quantity = number;

    cout << endl;
    cout << "Enter the Retail Cost for the item: ";
    getline (cin , word);
    number = atoi(word.c_str());
    vec[choice-1].retailCost = number;

    cout << endl;
    cout << "Enter the Wholesale Cost for the item: ";
    getline (cin , word);
    number = atoi(word.c_str());
    vec[choice-1].wholesaleCost = number;

    cout << endl;
    cout << "Enter current date: ";
    getline (cin , word);
    vec[choice-1].dateAdded = word;

    system("cls");

    cout << "Item edited successfully! " << endl;

    return vec;
}

template<typename T>
vector<T> deleteRecord(vector<T> &vec)
{
    if (!vec.size()) { cout << "There are no items to delete!" << endl << endl; return vec; }
    printItemDescriptions(vec);

    string word;
    int choice;

    cout << "Choose item to delete: ";

    getline( cin, word);

    choice = atoi(word.c_str());

    vec.erase (vec.begin()+choice-1);
    return vec;
}
#包括“stdafx.h”
#包括
#包括
#包括
#包括
使用名称空间系统;
使用名称空间std;
#布拉格语hdrstop
bool-isValidChoice(int-size,int-choice);
bool checkFileEmpty();
模板
void writeVector(流和流、常量向量和向量);
模板
矢量读取矢量(ifstream&in);
模板
矢量附加项(矢量和矢量);
模板
无效打印项目描述(矢量和矢量);
模板
int显示记录(矢量和矢量);
模板
矢量编辑记录(矢量和矢量);
模板
向量删除记录(向量和向量);
结构目录项{
字符串描述;
整数;
批发成本;
零售成本;
已添加字符串;
} ;
内部主(空)
{
库特

打开文件进行写入。默认情况下,它将从一开始就删除以前存在的任何内容。首先,使用与正在读取的文件不同的输出文件。

尝试添加接近案例6的语句:

case 6:
        out.close();
        return 0;
我很确定没有调用close,因为返回将在到达该语句之前退出main。如果文件未关闭,则会留下一个未刷新的缓冲区,我怀疑这会导致数据未写入


您应该在while循环之前移动open to,并从while循环中删除out.close(),因为它将在第一次菜单选择后关闭文件。

检查文件是否为空或无法打开

bool IsEmpty( const std::string & filename ) {

   std::ifstream ifs( filename.c_str() );

   if ( ifs.is_open() ) {
      std::string line;
      return ! std::getline( ifs, line );
   }
   else {
      return true;
   }
}

你最好把气流开闭的方向移到第五箱里

在这里,您可以在每次while迭代中创建一个新文件

case 5:
        {
            ofstream out("data.dat");
            writeVector(out , structList);
            out.close();
        }
        break;

好吧。我明白你的意思。我添加了它。但这并不能解决每次我选择菜单项时文件被擦除的问题。你可以将ios::app添加到打开的部分,以确保它附加,即流输出(“data.dat”,ios::app);另外,通过将“打开”移动到的外部,而它只会打开一次并关闭一次,从而不会一直覆盖.out.close()将在out的析构函数中调用。这就是我的整个问题的基础。当我将open移到while之外时,它就不再工作了。每当我保存时,都不会将任何内容写入文件!我试图得到以下错误:1>\Project 5.cpp(103):错误C2360:“case”标签跳过了“out”的初始化第105行是什么?我怀疑您需要删除的是另一个关闭(以及删除初始打开(构造函数)。投票,因为这比我的解决方案好-您应该只打开需要的文件。OMG。是这样的情况5:{}花括号让我可以创建一个流。我甚至不知道你能做到。谢谢你。{}也经常用于减少局部变量的作用域,这里需要它们来允许case语句中的变量声明。我尝试了你所说的。我仍然会在程序加载时崩溃,因为我的向量被设置为2亿…出于某种原因,它并没有阻止大小的设置。没关系。我刚刚让它工作了。谢谢。哇,你你真是个天才。
case 5:
        {
            ofstream out("data.dat");
            writeVector(out , structList);
            out.close();
        }
        break;