Fstream不会保存文件中的最后一个单词,也不会从文件中读取
Fstream doesnt save the last word in the file and it doesnt read from the file, too
这是一个在文件中注册游戏的简单代码,但有两个问题。
首先,参数或属性"classification"没有保存在文件中。
第二,当我从文件中读取时,内容不会显示。
在评论之前,你必须知道这是我第一次使用文件,我正在努力自学。
我知道这段代码缺乏模块性,我应该声明一个对象的指针向量,而不是指向对象,或者我应该声明智能指针,但我只是想向你展示我在文件中遇到的问题。
非常感谢任何帮助
#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);
问题不在于将输入的"分类"保存在文件中。问题是你把它读错了变量。
相关文章:
- 使用新行和不使用新行读取文件
- 读取文件并输入到矢量中
- 读取文件的最后一行并输入到链接列表时出错
- 为什么在读取文件大小时文件IO速度会发生变化
- 读取文件时运行时的未知行为
- 如何逐行读取文件,每行中的内容都用空格分隔并将其写入新文件中
- 读取文件中所有可能的十六进制 16 字节序列并打印每个序列
- C++ 读取文件读取文件不正确
- 读取文件并将其存储在unordered_map中时出现问题
- 读取文件时无法使用 OpenMP 获得加速
- 使用istringstearm和get行缓慢读取文件
- 如何继续读取不同功能中的文件,而不是从头开始再次读取文件?
- 读取文件时引发异常
- 从标准输入读取文件后读取用户输入
- 在读取文件后重置句柄
- 如何在C++编译时读取文件?
- std::ifstream 在读取文件中最后一项时设置 eofbit,但仅在读取数值类型时发生
- 读取文件在第二次调用时返回INVALID_HANDLE
- 通过指针读取文件
- 逐行读取文件,并将数据插入变量和数组中