I'm trying to figure out how to write an int (as a record number) and a string (up to 12 characters) into a binary file. So in one project the binary file is created with all 5 records written to it, with blank data, eg string is empty. In the next project I ask for user input indicating which record to update and what string to store in the file. Then the next project displays only the records that have data stored in them.

The problem I'm having is, I think I'm writing the string to the file incorrectly. When I run the ReadBinaryFile program, it displays the record numbers correctly, but blank data for the string entries. How do I properly store a random-sized string, up to 12 characters into this file? I have posted the files I have as well.

Here is the part where I store the data to the file:

Rivera rivy;
int recordNum;
cin >> recordNum;
...
cout << "Enter word\n? ";
cin >> word;
		
rivy.setKey(recordNum);
rivy.setWord(word, 0, 12);
		
lamefile.seekp((rivy.getKey() - 1) * sizeof(Rivera));

//rivy is a Rivera obj; Rivera object contains an int and a string
lamefile.write(reinterpret_cast<const char*>(&rivy), sizeof(Rivera));
		
cout << "Enter Record Number: (1-5, 0 to quit0\n? ";
cin >> recordNum;

PS: This isn't homework. I am following along in C++ How to Program 5th Ed. There is a code complete exercise in the book. I am trying to do this using strings though, rather than const char*. Since it's giving me trouble, I'm just interested in getting this right while I learn more about strings and fstreams. TIA!

you can't write std::string objects to a binary file like that. The easiest way to simplify your program is to use a char array instead of std::string. Now in the class constructure initialize that char array to all 0s.

class Rivera
{
public:
	Rivera();
	
	void setKey(const int);
	int getKey() const;
	
	void setWord(const string&);
	string getWord() const;
	
private:
	int id;
	char palabra[13];
};

I see. I guess that's why the book example used a char array as well. Thank You!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.