Search code examples
c++stringbinarycrc

I want to get the encoded string as output . But not able to


Input:

101101110
1101

Expected Ouput:

000000000011

My output:

It just keeps on taking the input.and not showing any output.

Please help me . what is wrong with my code. Any help would be aprreciated.I have given the names of the variables such that its easy to understand.This code is only for the senders side.

 #include <iostream>

using namespace std;

int main()
{
        string input;
        string polynomial;
        string encoded="";
        cin>>input;
        cin>>polynomial;
        int input_len=input.length();
        int poly_len=polynomial.length();
        encoded=encoded+input;
        for(int i=1;i<=poly_len-1;i++){
            encoded=encoded+'0';
        }
        for(int i=0;i<=encoded.length()-poly_len;){
            for(int j=0;j<poly_len;j++){
                if(encoded[i+j]==polynomial[j]){
                    encoded[i+j]=='0';
                }
                else{
                    encoded[i+j]=='1';
                }
            }
            while(i<encoded.length() && encoded[i]!='1'){
                i++;
            }
        }
        cout<<encoded;
    return 0;
}

Solution

  • Look at these lines properly:

    if (encoded[i + j] == polynomial[j]) {
        encoded[i + j] == '0'; // Line 1
    }
    else {
        encoded[i + j] == '1'; // Line 2
    }
    

    See? You are using == while you should be using =. == is a comparison operator which returns a boolean (true/false). It does not assign values. So to fix your problem, replace the above lines with:

    if (encoded[i + j] == polynomial[j]) {
        encoded[i + j] = '0'; // Replaced == with =
    }
    else {
        encoded[i + j] = '1'; // Replaced == with =
    }
    

    This should fix your problem.