gpt4 book ai didi

c++ - Fstream 不保存文件中的最后一个单词,也不从文件中读取

转载 作者:太空宇宙 更新时间:2023-11-04 13:17:57 25 4
gpt4 key购买 nike

这是一个在文件中注册游戏的简单代码,但是有两个问题。

首先,参数或属性“分类”没有保存在文件中。

其次,当我从文件中读取时,内容未显示。

发表评论之前,您必须知道这是我第一次使用文件,我正在努力自学。

而且我知道这段代码缺乏模块化,我应该声明一个对象指针 vector ,而不是指向对象的指针,或者我应该声明智能指针,但我只是想向您展示我在文件中遇到的问题。

非常感谢任何帮助

#include <iostream>
#include <vector>
#include <fstream>
#include <string>

using std::string;
using std::cout;
using std::vector;
using std::cin;
using std::endl;
using std::getline;
using std::fstream;

struct Games
{
string name;
string gender;
string clasification;
int year;
};

struct VectorGames
{
vector<Games>VectorForGames;
void InsertGame(string n, string g, string c, int y)
{
Games New = Games();
New.name = n;
New.gender = g;
New.clasification = c;
New.year = y;
VectorForGames.push_back(New);
}
};

int main()
{
string name;
string gender;
string clasification;
int year = 0;
int option = 0;
VectorGames V;
fstream File("SavedGames.txt", fstream::in | fstream::out | fstream::app | fstream::ate);
do
{
cout << "1. Register a game " << endl
<< "2. Show the list of games registered" << endl
<< "3. Exit " << endl;
cout << "Type in your option: ";
cin >> option;
cin.get();

switch (option)
{
case 1:
{
cout << "Type in the name: ";
getline(cin, name);
cout << "Type in the gender: ";
getline(cin, gender);
cout << "Type in the clasification: ";
getline(cin, gender);
cout << "Type in the year: ";
cin >> year;
V.InsertGame(name, gender, clasification, year);
if (File.is_open())
File << "Name: " << name << " Gender: " << gender
<< " Clasification: " << clasification << " Year: " << year << endl;
break;
}

case 2:
{
string temporal;
while (getline(File, temporal))
{
cout << temporal << endl;
}
break;
}

case 3: File.close();
break;

default: cout << "Try again" << endl;

}

} while (option != 3);

return 0;

最佳答案

    cout << "Type in the gender: ";
getline(cin, gender);
cout << "Type in the clasification: ";
getline(cin, gender);

问题不在于将输入的“分类”保存在文件中。问题是您将其读入了错误的变量。

关于c++ - Fstream 不保存文件中的最后一个单词,也不从文件中读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36511899/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com