c++ - 字符串与字符数组;为什么我得到不同的结果?
问题描述
我在我的文件中保存了 2 个输入, 1st:Hello
05
和 2nd: Ciao
07
。当我std::string
用于分配我的字符串(在类中)时,代码会正确输出第一个字符串和第一个整数值,但对于第二个字符串,它会给出一些垃圾值或一些空格,并且当我使用char array
而不是std::string
字符串和整数输出时正确。
#include <iostream>
#include <fstream>
#include <string>
class value
{
int val;
// char text[20];
std::string text;
public:
void read_Data()
{
std::cout << "ENTER TEXT and ANY INT VALUE: " << std::endl;
std::cin >> text >> val;
push_toFile();
}
void push_toFile()
{
std::ofstream fout;
fout.open("val.txt", std::ios::app);
fout.write((char *)this, sizeof(*this));
fout.close();
}
void pull_fromFile()
{
std::ifstream fin;
fin.open("val.txt", std::ios::app);
fin.read((char *)this, sizeof(*this));
while (!fin.eof())
{
show_Data();
fin.read((char *)this, sizeof(*this));
}
}
void show_Data()
{
std::cout << text << " " << val << '\n';
}
};
int main()
{
/* I have saved 2 inputs in my file, 1st: "Hello" 05 and 2nd: "Ciao" 07
using these two following(commented) functions. */
// value val1, val2;
// val1.read_Data();
// val2.read_Data();
/* when I'm using std::string for assigning my string, then code
outputs correctly for first string and first integer value but for second string it gives some
garbage value or some blank spaces....and when I used char array instead of std::string both
string & integer ouputs correctly */
value show_allData;
show_allData.pull_fromFile();
return (0);
}
解决方案
sizeof(*this)
与 中的字符数std::string
无关,但与 中的元素数有关char text[20];
。
您需要为std::string
case 复制的字符数是text.size() + 1
,多余的一个用于NUL
终止符。(您需要注意确保您的流写入正确处理它。)
也就是说,你应该fout << text;
在这样的情况下使用字符串std::string
的内容被写入。
推荐阅读
- node.js - 如何从渲染 html Sails js 创建文件
- visual-studio-code - 禁用 VSCode 提示:“是否要保存工作区配置”?
- wordpress - Echo 变量 ID 在 WordPress 中不起作用
- php - 我的正则表达式函数似乎是正确的,但它不起作用
- html - 制作水平按钮滚动条
- regex - 在 Ansible/Jinja 中,有没有一种方法可以使用 k:v 对的字典将字符串替换为整数?
- styles - 我该怎么做才能使 MD 文件在 Notepad++ 中更明显?
- mainframe - 如何在 JCL 中使用 listcat 列出输出文件中的所有文件
- python - EOFError:输入pickle.load用完,文件不为空
- mysql - Mysql - 返回目标 JSON 文档中包含 JSON 文档的行数