libprotobuf Error: Missing Required Fields

1,405 views
Skip to first unread message

Kavi

unread,
Jun 12, 2011, 6:58:28 PM6/12/11
to Protocol Buffers
I have this simple .proto file:

package test;

message Person {
required string name = 1;
required int32 age = 2;
}

I have this test file to write contents:

#include <iostream>
#include <fstream>
#include <string>
#include "test.pb.h"
#include <stdio.h>
using namespace std;

int main(){

string data,dummy;
test::Person kavi;
kavi.set_name("Kavi");
kavi.set_age(22);
ofstream out;
out.open("data.dat");


kavi.SerializeToString(&data);
out<<data<<endl;
out.close();

ifstream in;
in.open("data.dat");
in>>dummy;
cout<<dummy<<endl;
cout<<data<<endl;

test::Person second;
second.ParseFromString(data);
cout<<second.name();
cout<<"\n";
cout<<second.age();
in.close();


return 0;
}

When I tried to compile this, it works fine. But when I change the
line second.ParseFromString(data) to second.ParseFromString(dummy), it
compiles fine and on executing, it throws the following error:

"libprotobuf ERROR google/protobuf/message_lite.cc:123] Can't parse
message of type "test.Person" because it is missing required fields:
name, age"

Basically the strings dummy and data are the same. So why does it
throw the error?? Somebody please suggest a fix.

Thanks in advance,
Kavi

Jason Hsueh

unread,
Jun 13, 2011, 10:01:14 AM6/13/11
to Kavi, Protocol Buffers
On Sun, Jun 12, 2011 at 3:58 PM, Kavi <targe...@gmail.com> wrote:

Basically the strings dummy and data are the same. So why does it
throw the error?? Somebody please suggest a fix.


Have you verified that these strings are actually the same? (By doing a direct comparison, rather than printing them to cout) The serialization contains binary data; you need to open the ifstream with ios::binary, and you typically don't want to use the stream operators. You can also use the other parsing entry points like ParseFromFileDescriptor or ParseFromIstream.

 
Thanks in advance,
Kavi

--
You received this message because you are subscribed to the Google Groups "Protocol Buffers" group.
To post to this group, send email to prot...@googlegroups.com.
To unsubscribe from this group, send email to protobuf+u...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/protobuf?hl=en.


Reply all
Reply to author
Forward
0 new messages