simple string problem - Noob
-
Writing a simple Win32 Console App to read the header of a WAV file. Aim was to test my understanding of File IO, but seem to have uncovered a problem with my understanding of strings instead when I got some unexpected output. :-O The code below results in output such as: RIFF RIFF╠╠╠╠¿ ↕ If
char ch[4]
defines ch as a character array of size 4, why doescout << ch
appear to output additional bytes beyond the end of ch?int main(int argc, char *argv[])
{
char ch[4];
register int i;
if(argc!=2)
{
cout << "Usage: WavInfo \n";
return 1;
}
ifstream in(argv[1], ios::in | ios::binary);
if(!in)
{
cout << "Cannot open file.\n";
return 1;
}
in.read(ch,4);
for(i=0; i<4; i++){cout << ch[i];}
cout << "\n";
cout << ch << "\n";}
-
Writing a simple Win32 Console App to read the header of a WAV file. Aim was to test my understanding of File IO, but seem to have uncovered a problem with my understanding of strings instead when I got some unexpected output. :-O The code below results in output such as: RIFF RIFF╠╠╠╠¿ ↕ If
char ch[4]
defines ch as a character array of size 4, why doescout << ch
appear to output additional bytes beyond the end of ch?int main(int argc, char *argv[])
{
char ch[4];
register int i;
if(argc!=2)
{
cout << "Usage: WavInfo \n";
return 1;
}
ifstream in(argv[1], ios::in | ios::binary);
if(!in)
{
cout << "Cannot open file.\n";
return 1;
}
in.read(ch,4);
for(i=0; i<4; i++){cout << ch[i];}
cout << "\n";
cout << ch << "\n";}
-
Writing a simple Win32 Console App to read the header of a WAV file. Aim was to test my understanding of File IO, but seem to have uncovered a problem with my understanding of strings instead when I got some unexpected output. :-O The code below results in output such as: RIFF RIFF╠╠╠╠¿ ↕ If
char ch[4]
defines ch as a character array of size 4, why doescout << ch
appear to output additional bytes beyond the end of ch?int main(int argc, char *argv[])
{
char ch[4];
register int i;
if(argc!=2)
{
cout << "Usage: WavInfo \n";
return 1;
}
ifstream in(argv[1], ios::in | ios::binary);
if(!in)
{
cout << "Cannot open file.\n";
return 1;
}
in.read(ch,4);
for(i=0; i<4; i++){cout << ch[i];}
cout << "\n";
cout << ch << "\n";}
-
C/C++ use the null-character to indicate the end of a string, so in memory, the string would be stored as 'R' 'I' 'F' 'F' '\0'. So to store 4 characters, you need a string
char ch[5];
Thanks Thaddeus. Problem solved!
-
Strings have to be zero terminated. Replace
char ch[4];
with
char ch[5];
ch[4] = 0;or something similar to have a zero after the string data.
Thanks guyee. Problem solved!