zspar
zspar

Reputation: 23

White Space Removal At the end of a line C++

The code is supposed to multiply two matrices and print the output. It works fine except for it prints an extra space at the end of each line, and the online submission service wont accept it with that space. Any help would be appreciated.

#include <iostream>
#include <string>
#include <sstream>
using namespace std;
void matrixMultiply(int A[][10],int m,int n,int B[][10],int p,int q)
{
    int sum=0;
    int **product ;
    product = new int*[m];
    for(int i=0;i<q;i++)
        product[i] = new int[q];

    if(n!=p)
    {
        cout<<"The two matrices have incompatible dimensions."<<endl;
        return;
    }
    cout<<"The product is:\n";
    for(int i=0;i<m;i++)
    {
        for(int j=0;j<q;j++)
        {
            for(int k=0;k<p;k++)
            {
                sum+=A[i][k]*B[k][j];
            }
            product[i][j]=sum;
            sum=0;
        }
    }


    for(int i=0;i<m;i++)
    {
        for(int j=0;j<q;j++)
            cout<<product[i][j]<<" "; //This is where the problem is
            cout<<endl;
    }
}

int main()
{

    int m=0,n=0;
    int p=0,q=0;

    int A[10][10];
    int B[10][10];

    string val1, val2;

    string m1=" ",m2=" ";
    string choice = "y";
    cout<<"Enter first matrix:"<<endl;
    do
    {
        getline(cin, m1);
        if(m1.compare("")==0)
            break;
        stringstream ss(m1);
        n=0;
        while(ss>>val1)
        {
            A[m][n]=stoi(val1);
            n++;
        }
        m++;

    }while(cin.peek());
    cout<<"Enter second matrix:"<<endl;
    do
    {
        getline(cin, m2);
        if(m2.compare("")==0)
            break;
        stringstream ss(m2);
        q = 0;
        while(ss>>val2)
        {
            B[p][q]=stoi(val2);
            q++;
        }
        p++;

    }while(cin.peek());


    matrixMultiply(A,m,n,B,p,q);

    return 0;
}

Sample

Enter first matrix:
1 2 3
4 5 6

Enter second matrix:
7 8
9 0
1 2

The product is:
28 14 <- extra space
79 44 <- extra space

Upvotes: 0

Views: 1440

Answers (1)

Barry
Barry

Reputation: 303057

First of all, let's add some missing braces, since the endl clearly isn't associated with the loop:

for(int i=0;i<m;i++)
{
    for(int j=0;j<q;j++)
    {
        cout << product[i][j] << " "; //This is where the problem is
    }
    cout << endl;
}

Good habit to get into. In any event, if the problem is the trailing space just change your logic around. Instead of always printing a space after every element - print one before every element, so the inner loop becomes:

for (int j=0; j<q; ++j) {
    cout << ' ' << product[i][j];
}

And now we just have to deal with the extra leading space... which is easy, don't print a space on the first element:

for (int j=0; j<q; ++j) {
    if (j) {
        cout << ' ';
    }
    cout << product[i][j];
}

Upvotes: 4

Related Questions