简体   繁体   中英

String vs Char array; Why I'm getting diffrent results?

I have saved 2 inputs in my file, 1st: Hello 05 and 2nd: Ciao 07 . When I'm using std::string for assigning my string(in class), 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 outputs correctly.

#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) is not related to the number of characters in the std::string but would be related to the number of elements in char text[20]; .

The number of characters you need to copy for the std::string case is text.size() + 1 , the extra one is for the NUL terminator. (You need to to take care to make sure your stream writing handles it correctly.)

That said, you should be using fout << text; in the case of the std::string so the contents of the string are written.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM