question about read, write I/O streams

hi everybody i was just having such a frustrating question concerning using read and write of I/O streams.
here is the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;


int main(int argc, char *argv[])
{char k[4];char h[4];
strcpy(k,"cccc");
//1st part writing
ofstream out("yyy",ios::out | ios::binary);
out.write((char *)k,sizeof(k));
out.close();
for(int i=0;i<4;i++)
   k[i]='0';
cout<<k<<endl;
//2nd part:reading
ifstream in("yyy",ios::in | ios::binary);
in.read((char *)k,sizeof(k));
for(int i=0;i<4;i++)
    cout<<k[i]<<' ';
if(!strcmp(k,"cccc")){cout<<"that's it"<<endl;}
    system("PAUSE");
    return EXIT_SUCCESS;
}


this works well
but when i use h[4] instead of k[4] while reading from the file (2nd part),the (strcmp statement returns one (which means not identical )although when i display the contents of h[4] it is "cccc"(the same that i compare with).


what i mean is that when i use that code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;

int main(int argc, char *argv[])
{char k[4];char h[4];
strcpy(k,"cccc");
ofstream out("yyy",ios::out | ios::binary);
out.write((char *)k,sizeof(k));
out.close();
for(int i=0;i<4;i++)
   k[i]='0';
cout<<k<<endl;
ifstream in("yyy",ios::in | ios::binary);
in.read((char *)h,sizeof(h));//this is the difference
for(int i=0;i<4;i++)
    cout<<h[i]<<' ';
if(!strcmp(h,"cccc")){cout<<"that's it"<<endl;}
    system("PAUSE");
    return EXIT_SUCCESS;
}


the result is that the content of h[i]="cccc" but no cout<<"that's it" will be executed so why???????????????????????
thanks in advance.
Last edited on
Please re-post this using the appropriate coding tags. The current format is a pain to read and demotivates us from helping... =/
There are a couple weird things here:

1) http://cplusplus.com/reference/clibrary/cstring/strcmp/

Consult this link for reference on strcmp. As you can see, it returns an integral value, and (more specifically) returns zero if the two strings are equal. Stating !strcmp doesn't really make sense in this case. Thus, for line 20, you want

if(strcmp(h,"cccc")==0)

2) Try a cout of just h itself (since that is what you're actually comparing). It is definitely not equal to the constant char "cccc". Unfortunately, I can't explain where the bug is at the moment, but will try to get back to you later.

Hope that helps for now.
Topic archived. No new replies allowed.