简体   繁体   English

即使应该,我的代码也不会覆盖文本文件?

[英]My code isn't overwriting the text file, even though it should be?

We did a very similar type of code in C++ class but my version isn't working right, even though it is line-by-line (almost) the same. 我们在C ++类中执行了非常相似的代码类型,但是即使逐行(几乎)相同,我的版本也无法正常工作。

My code is meant to save a user's Pokemon and they can add and delete as they please. 我的代码旨在保存用户的口袋妖怪,他们可以根据需要添加和删除。 My display function is working but my add and delete function are not. 我的显示功能正常工作,但我的添加和删除功能无效。 All the files are opening, but it's not overwriting the file like it's supposed to. 所有文件都在打开,但是并没有像预期的那样覆盖文件。 Really unsure of what to do, I'm very much a beginner and I don't know much. 真的不确定该怎么做,我是个初学者,并不了解很多。

Here is what I've got so far: 这是到目前为止我得到的:

string name[100];
string type[100];
int level[100];
string newPokemon;
string newType;
int newLevel;
ifstream fin;
ofstream fout;
int numberOfPokemon = 0;
//Input Pokemon Info
cout << "Name of Pokemon: ";
getline(cin, newPokemon);
cin.ignore(100, '\n');
cout << "Pokemon type: ";
getline(cin, newType);
cin.ignore(100, '\n');
cout << "Pokemon level: "; //weird gap between "Pokemon type" and "pokemon level". I have to press enter twice from "pokemon type" to get to "pokemon level"
cin >> newLevel;
cin.ignore(5, '\n');
fin.open("pokemon.txt");
//Put file in array
if (fin.is_open())
{
    while (isalnum(fin.peek()) && numberOfPokemon < 100)
    {
        getline(fin, name[numberOfPokemon]);
        getline(fin, type[numberOfPokemon]);
        fin >> level[numberOfPokemon];
        fin.ignore(100, '\n');
        if (name[numberOfPokemon] != newPokemon)
            numberOfPokemon++;
    }
    fin.close();
}
//Output file
fout.open("pokemon.txt");
if (fout.is_open())
{
    for (int i = 0; i < numberOfPokemon; i++)
    {
        fout << name[i] << "\n";
        fout << type[i] << "\n";
        fout << level[i] << "\n";

    }
    //Tack on new piece
    fout << newPokemon << "\n";
    fout << newType << "\n";
    fout << newLevel << "\n";
    fout.close();
    cout << "Add Successful\n";
}
else
{
    cout << "Add Failure\n";
}

and now my delete function: 现在我的删除功能:

string name[100];
string type[100];
int level[100];
int pokemonCount = 0;
string deletedPokemon = "";
bool found = false;

ifstream fin;

cout << "Which Pokemon would you like to delete?" << endl;
getline(cin, deletedPokemon);
cin.ignore(5, '\n');

fin.open("pokemon.txt");
if (fin.is_open())
{
    while (isalnum(fin.peek()))
    {
        getline(fin, name[pokemonCount]);
        getline(fin, type[pokemonCount]);
        fin >> level[pokemonCount];
        fin.clear();
        fin.ignore(100, '\n');
        if (deletedPokemon == name[pokemonCount])
        {
            pokemonCount--;
            found = true;
        }
        pokemonCount++;
    }
    fin.close();
    cout << "ya the file opened" << endl; //always appears
}

ofstream fout;
fout.open("pokemon.txt");
if (fout.is_open())
{
    for (int i = 0; i < pokemonCount; i++)
    {
        fout << name[i] << "\n";
        fout << type[i] << "\n";
        fout << level[i] << endl;
    }
    fout.close();
    cout << "pokemon removed\n";
    cout << "the file opened."; //it is returning that the file opened in both occasions in this function but nothing is happening!
}
else
{
   cout << "removal failure";
   cout << "The file didn't open";
}
return found;

at the end of this function (if I chose to delete one), it will offer the "Would you like to add a Pokemon?" 在此功能结束时(如果我选择删除一个),它将显示“您是否要添加口袋妖怪?” but it wont let me input an answer and it will just end the program. 但它不会让我输入答案,只会结束程序。

The default behaviour of ofstream::open is to simply open the file for reading and writing. ofstream::open的默认行为是简单地打开文件进行读写。 If you want to overwrite the file, you need to specify it in your call to open . 如果要覆盖文件,则需要在open调用中指定它。

fout.open("pokemon.txt", ios_base::in|ios_base::out|ios_base::trunc);

Make sure your file is not marked as read-only under properties. 确保您的文件未在属性下标记为只读。

Also, there is a bug in your delete function: 此外,删除功能中还有一个错误:

The bfound should be replace with nDelete pokemon and when you write out the file: 当您写出文件时,应将bfound替换为nDelete pokemon:

    if (deletedPokemon == name[pokemonCount])
    {
        pokemonCount--;
        found = true;
        nDeleteIndex = i;
    }
....
    for (int i = 0; i < pokemonCount; i++)
    {

    if(i == nDeleteIndex)
        continue;
    fout << name[i] << "\n";
    fout << type[i] << "\n";
    fout << level[i] << endl;
    }

Right now it will re-write all your pokemons without skipping the one you want to delete! 现在,它将重新编写您所有的宠物小精灵,而不会跳过您要删除的小精灵!

Also, what happens if the user has 155 pokemons for a full index. 同样,如果用户拥有155个完整索引的神奇宝贝,会发生什么。 You want to use: 您要使用:

 std::vector<string> names;
 ....
 string szPokemon;
 getline(fin, name[numberOfPokemon]);
 names.push_back(szPokemon);

Thus you no longer have a limit ! 因此,您不再有限制!

Here is much cleaner code, its much more maintainable and whenever you add/remove a field from the pokemon (Shiny? Male/Female ? Unique ?) you will be able to easily do it inside the CPokemonObject instead of having to copy paste the code 100 times. 这是更简洁的代码,它更易于维护,每当您从pokemon中添加/删除一个字段(Shiny?Male / Female?Unique?)时,您都可以轻松地在CPokemonObject中完成它,而不必复制粘贴代码100倍

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>

using namespace std;
#define POKEMON_FILE "Pokemon.txt"

class CPokemon
{
public:
    string szName;
    string szType;
    int nLevel;
    CPokemon() : szName("Pika"), nLevel(10), szType("Lightning")
    {};

    void Read(ifstream &file)
    {
        file >> szName;
        file >> szType;
        file >> nLevel;
    };

    void Write(ofstream &file)
    {
        file << szName << endl;
        file << szType << endl;
        file << nLevel << endl;
    };

    void CreatePokemon()
    {
        //Input Pokemon Info
        cout << "Name of Pokemon: ";
        getline(cin, szName);
        cout << "Pokemon type: ";
        getline(cin, szType);
        cout << "Pokemon level: "; //weird gap between "Pokemon type" and "pokemon level". I have to press enter twice from "pokemon type" to get to "pokemon level"
        cin >> nLevel;
    }
};

void WritePokemons(vector<CPokemon>& Pokemons)
{
    ofstream fout;
    fout.open(POKEMON_FILE);

    //check the file open
    if (!fout.is_open())
    {
        cout << "removal failure";
        cout << "The file didn't open";
        return;
    }

    //Write out all the pokemons
    for (unsigned int i = 0; i < Pokemons.size(); i++)  
        Pokemons[i].Write(fout);

    fout.close();
}

void ReadPokemons(vector<CPokemon>& Pokemons)
{
    ifstream fin;
    fin.open(POKEMON_FILE);
    if (fin.is_open())
    {
        while (isalnum(fin.peek()))
        {
            CPokemon Pokemon;
            Pokemon.Read(fin);
            Pokemons.push_back(Pokemon);
        }
        fin.close();
        cout << "ya the file opened" << endl; //always appears
    }
}

bool DeletePokemon()
{
    vector<CPokemon> Pokemons;

    string szPokemonToDelete = "";
    cout << "Which Pokemon would you like to delete?" << endl;
    cin >> szPokemonToDelete;

    //Read all pokemons
    ReadPokemons(Pokemons);

    ofstream fout;
    fout.open("pokemon.txt");

    //check the file open
    if (!fout.is_open())
    {
        cout << "removal failure";
        cout << "The file didn't open";
        return false;
    }

    bool bFound = false;
    for (unsigned int i = 0; i < Pokemons.size(); i++)      
    {
        //Skip the pokemon to delete
        if(Pokemons[i].szName == szPokemonToDelete)
        {
            bFound = true; //we found the pokemon to delete
            continue;
        }

        Pokemons[i].Write(fout);
    }

    fout.close();

    return bFound;
}

void AddPokemon()
{
    vector<CPokemon> Pokemons;

    //Read all pokemons from the file
    ReadPokemons(Pokemons);

    //Create the new porkemon
    CPokemon Pokemon;
    Pokemon.CreatePokemon();

    //Add the pokemon to the list
    Pokemons.push_back(Pokemon);

    //Output file
    WritePokemons(Pokemons);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 项目没有显示,即使应该显示 - Item isn't displayed even though it should 即使代码看起来正确,也没有创建第二个文件 - A second file isn't being created even though the code seems right Code :: Blocks-Linux-即使“ main.cpp”文件中没有该文件,也会打印“ Hello World” - Code::Blocks - Linux - prints “Hello World” even though it isn't in the “main.cpp” file 为什么即使我的MFC应用程序不是多线程的,Visual Studio仍显示多个线程? - Why does Visual Studio show multiple threads even though my MFC app isn't multithreaded? 为什么我的代码只显示数组中的最后一个元素,即使它应该显示具有最多字符的元素 - Why is it that my code is only showing the last element in the array even though It should be showing the element with the most amount of characters 即使GetThreadPriority指示SetThreadPriority不能正常工作 - SetThreadPriority isn't working even though GetThreadPriority indicates that it is 即使我的 main 没有调用任何东西(C++),我的可执行文件也很大 - my executable file is so big even though my main doesn't call anything (C++) 为什么strcmp()无法正常运行? C ++ - Why isn't strcmp() working as I though it should? c++ 即使它应该,c ++ map也不会返回end() - c++ map doesn't return end() even though it should C ++错误代码C2065:“ <class name> &#39;未声明的标识符,即使应在另一个.h文件中声明 - C++ error code C2065: '<class name>' undeclared identifier, even though it should be declared in another .h-file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM