首页 > 解决方案 > 字符串与字符数组;为什么我得到不同的结果?

问题描述

我在我的文件中保存了 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);
}

标签: c++file

解决方案


sizeof(*this)与 中的字符数std::string无关,但与 中的元素数有关char text[20];

您需要为std::stringcase 复制的字符数是text.size() + 1,多余的一个用于NUL终止符。(您需要注意确保您的流写入正确处理它。)

也就是说,你应该fout << text;在这样的情况下使用字符串std::string内容被写入。


推荐阅读