1

I am sending array of 5 strings into a function that will write them into a binary file. My problem is how can I do that? How can I check the size of array if I am sending it by a pointer? I included #include <string> and using namespace std;.

void my_func(string *array, int n)
{
ofstream my_file("file.bin", ios_base::binary);
if (!my_file)
{
    cout << "error" << endl;
    return;
}
my_file.write((char*)array, n*sizeof(string));
my_file.close();
}

void fun1()
{
string array[5];
for (int i = 0; i < 5; i++)
{
    cout << "enter word " << i + 1 << ": ";
    getline(cin, array[i]);
}
my_func(array,5);
return;
}

So this works, but I use too many bytes for nothing, I want to take correct amount of bytes. Or if there is an easy way to do all this, I would be thankful. And please give me a school example, I am a student.

Output:

5
  • 1
    How is string defined? Commented Jan 30, 2016 at 20:51
  • @LogicStuff i will post a picture Commented Jan 30, 2016 at 20:52
  • You are writing the very implementation of std::string to the file instead of its contents. Commented Jan 30, 2016 at 20:52
  • It is not clear that string is std::string, Lingxi. The OP hasn't given enough information to conclude that. Commented Jan 30, 2016 at 20:54
  • I edited the post with more information @PeteBecker . Commented Jan 30, 2016 at 21:02

1 Answer 1

2

I overwrite my answer, because first version was written with some misunderstanding

You can simply do it by this way.

void my_func(string *str_array, int n)
{
    ofstream my_file("file.bin", ios_base::binary);
    if (!my_file.is_open()) {
        cout << "error" << endl;
        return;
    }
    for (int i = 0; i < n; i++) {
        // If strings are null-terminated use +1 to separate them in file
        my_file.write(&str_array[i][0], str_array[i].length() + 1);
        // If strings aren't null-terminated write a null symbol after string
        // my_file.write("\0", 1);
    }
    my_file.close();
}

This one of common mistakes of beginners - sizeof(pointer type) expected it returns array size but pointer size will be returned.

Sign up to request clarification or add additional context in comments.

5 Comments

Given that a purpose of writing a file is normally so it can be subsequently read in, this is problematical. There is no way the reader can get length information in order to read. Unless the single string is ALL that is written to the file.
@Peter, it may be null-terminated string.
@ComradeAndrew but I want to write an array of strings, not just one string
@Kira, oh, sorry. So int n is number of this strings?
@ComradeAndrew thx you very much, yes that is what i was expecting. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.