I have a snip of the following code which should read the first 4 objects in a .wav file in order to eventually parse the header of the file. I know I'm doing something wrong here because the buffer always passes "RIFF" without printing out Riff is found
How should I use the Switch-case in order to find the correct array characters?
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "Nom: ";
string filename;
cout << "First Input filename:" << endl;
cin >> filename;
#pragma warning (disable : 4996)
FILE* InFile = fopen(filename.c_str(), "rb"); // Open wave file in read mode
char Buffer[4];
while (InFile) {
fread(Buffer, sizeof Buffer[0], 4, InFile);
switch (Buffer[4]) {
case 'R' +'I'+'F'+'F':
cout << "Riff is found " << endl;
case 'c' +'r'+ 'i'+ 'f' :
cout << "CRiff is found " << endl;
}
}
}
In contrast to languages such as C#, you cannot use strings in a switch
expression. You will have to use if
...else
statements in conjunction with std::memcmp
instead:
if ( std::memcmp( Buffer, "RIFF", 4 ) == 0 )
std::cout << "Riff is found.\n";
else if ( std::memcmp( Buffer, "crif", 4 ) == 0 )
std::cout << "CRiff is found.\n";
Note that std::memcmp
should only be used if you are sure that all character sequences are of the same length. Otherwise, it is safer to use std::strncmp
.
In your posted code, what is actually happening is the following:
The expression 'R'+'I'+'F'+'F'
will evaluate to the sum of the individual character codes of these letters. This is not what you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With