gpt4 book ai didi

C++ 将结构字符串保存到文本文件中

转载 作者:行者123 更新时间:2023-11-30 02:39:07 27 4
gpt4 key购买 nike

在我的程序中,我会保存高分以及以分秒为单位的时间。在我的代码中,我目前将其作为两个 int 存储在名为 highscore 的结构中。但是,当我显示输出时格式化时,这有点乏味。我想将时间显示为 12:02 而不是 12:2。在我的游戏中,我已经创建了一个名为 string clock 的变量,它已经用冒号格式化,我想要做的就是将它添加到我的文本文件中。

如何重构我的代码,使时间戳只有一个变量,并且格式正确?我希望能够通过直接调用结构将我的数据写入文件。

// Used for Highscores
struct highscore
{
char name[10];
int zombiesKilled;

// I would like these to be a single variable
int clockMin;
int clockSec;

char Date[10];
};

// I write the data like this:
highscore data;
// ...
data[playerScore].clockMin = clockData.minutes;
data[playerScore].clockSec = clockData.seconds;

streaming = fopen( "Highscores.dat", "wb" );
fwrite( data, sizeof(data), 1 , streaming);
// ...

最佳答案

看来您想简单地编写一个 C 字符串或 std::string使用 C 的 fwrite() 到一个文件功能。

这应该很容易,因为您的 C 字符串是符合 ASCII 格式的(没有 Unicode 有趣的事情):

//It appears you want to use C-style file I/O
FILE* file = NULL;
fopen("Highscores.dat", "wb");

//std::string has an internal C-string that you can access
std::string str = "01:00";
fwrite(str.c_str(), sizeof(char), sizeof(str.c_str()), file);
//You can also do this with regular C strings if you know the size.

我们也可以选择尝试使用 C++ 风格的文件 I/O 以获得更简洁的界面。

#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>

int main() {
std::string str = "00:11";

std::ofstream file("example.txt");

if (file.good()) {
file << str;
std::cout << "Wrote line to file example.txt.\n";
}
file.close();

//Let's check if we actually wrote the file.
std::ifstream read("example.txt");
std::string buffer;

if (read.good())
std::cout << "Opened example.txt.\n";
while(std::getline(read, buffer)) {
std::cout << buffer;
}

return 0;
}

此外,<chrono>中还有数据类型这对当时的情况很有帮助。

如果你希望能够做到这一点:

file << data_struct;

那么为 std::ostream 创建一个运算符重载就有意义了。

关于C++ 将结构字符串保存到文本文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30157472/

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