Rupinder Ghotra
Rupinder Ghotra

Reputation: 59

File not showing last Character of string when written in file

This snippet is part of a big program. The problem I am facing is that when I write a string to the file using "write" member function, it do not show last character of string:

#include <iostream>
#include <cstring>
#include <string>
#include <cctype>
#include <fstream>
#include <cstring>

using namespace std;

int main()
{

    fstream file1("/users/xxxxxxx/desktop/file1.txt", ios::out);
    string data;
    cout << "Enter string: " << endl;
    getline(cin, data);
    file1.write(reinterpret_cast<char*>(&data), data.size());
    //file1 << data;
    file1.close();
    return 0;
}

For Example: If Input String: "Hello World". On File it will show: "Hello Worl", But it does work fine if I input string using "file1 << data". Please help me in this

Upvotes: 0

Views: 190

Answers (2)

DigitalEye
DigitalEye

Reputation: 1565

Why would you cast the address of a string into a char*? This isn't a meaningful conversion--you are casting a std::basic_string<char>* to char*. I suspect you want to treat string as char* since write accepts const char* as parameter. You can access the character sequence stored in your data by doing data.c_str().

Upvotes: 0

user657267
user657267

Reputation: 21000

file1.write(reinterpret_cast<char*>(&data), data.size());

Don't do this, you are writing the string object itself to the file. if you really want to use write you have to get a pointer to the first char that the string holds, like this:

file1.write(data.data(), data.size());

Just use the << operator.

Upvotes: 2

Related Questions