Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a char buffer array as the case in switch-case C++?

Tags:

c++

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;
        }
    }
}
like image 596
Omar Avatar asked Jan 24 '23 05:01

Omar


1 Answers

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.

like image 52
Andreas Wenzel Avatar answered Jan 26 '23 17:01

Andreas Wenzel