c++ - 如何在 C++ 中将带有空格的字符数组写入二进制文件?以及如何阅读它们?
问题描述
现在我正在大学做我的课程项目。我需要帮助。我想创建一个简单的字典。我正在使用二进制文件方法来做到这一点。在下面的代码中,我试图编写也包含空格的文本行。但我得到错误的输出。有没有人可以帮助我将带有空格的文本写入二进制文件并阅读它们?
//These are global variables in my code
string sword;
string sdefinition;
这是我的课:
class Input
{
public:
char word[50];
char definition[300];
void input()
{
cout << "Enter a new word: ";
getline(cin, sword);
sword.copy(word, sword.size() + 1);
cout << "Enter the definition: ";
getline(cin, sdefinition);
sdefinition.copy(definition, sdefinition.size() + 1);
}
void output()
{
for (int i = 0; i < strlen(word); i++)
{cout << word[i];}
cout << endl;
for (int i = 0; i < strlen(definition); i++)
{cout << definition[i];}
cout << endl;
}
};
这是我的主要功能:
int main()
{
ofstream a("data", ios::app | ios::binary);
Input i;
i.input();
a.write((char*)&i, sizeof(i));
a.close();
ifstream b("data", ios::binary);
b.read((char*)&i, sizeof(i));
i.output();
b.close();
return 0;
}
解决方案
推荐阅读
- java - Servlet 在 IntellJ 上不起作用
- python - 为稀疏的 64 位无符号整数创建最小完美哈希
- c# - 转换位图 tp 图像
- android - java.lang.UnsatisfiedLinkError: 找不到 java.lang.String com.swoop.utility.ImageStabilizer.hello() 的实现
- php - 通过 MySQL 和 PDO 使用 PHP 的多级嵌套 JSON 输出
- sql-server - 在 SQL Server Management Studio (SSMS) 中关闭自动提交
- git - Git 存储库,其中脚本物理上位于另一个 git 存储库中
- python - 在打印命令中打印字符串时出现 Discord.py 错误
- f# - F# - 包含数字的字符串的自然排序
- php - 尝试使用 Laravel 迁移添加外键约束时出错