0

The following code is for printing the elements of a matrix in spiral order. The program works fine. The problem, however, is that the test compiler against which I'm checking the program, doesn't accept trailing white spaces at the end of the output. Could anyone give me some ideas as to how I can get around the last white space being added at the output?

#include <stdio.h>
#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main()
{
  string input;
  int value;
  int matrixA[10][10],matrixB[10][10],result[10][10];
  int k=0,l=0,m=0,n=0;
  int i=0,j=0;

  cout<<"Enter first matrix:\n";

   while(true)
{
    //Read string from keyboard
    getline(std::cin,input);
    if(input.empty())
    {
        break;
    }
    //Parse string using sring stream
    stringstream ss(input);
    j=0;
    while (ss >> value)
    {
        matrixA[i][j]=value;
        j++;
        if (ss.peek()==' ')
            ss.ignore();
    }
    i++;
}
 //Assign row and column length
k=i;
l=j;

cout<<"Enter second matrix:\n";
i=0;
while(true)
{
    //Read string from keyboard
    getline(std::cin,input);
    if(input.empty())
    {
        break;
    }
     //Parse string using sring stream
    stringstream ss(input);
    j=0;
    while (ss >> value)
    {
        matrixB[i][j]=value;
        j++;
        if (ss.peek()==' ')
            ss.ignore();
    }
    i++;
}
//Assign row and column length
m=i;
n=j;

bool first=true;
if(l==m)
{
    //Multiplication logic
    for(i=0;i<k;i++)
    {
        for(j=0;j<n;j++)
        {
            result[i][j]=0;
            for(int d=0;d<m;d++)
            {
                result[i][j]=result[i][j]+matrixA[i][d]*matrixB[d][j];

            }
        }
    }

     cout<<"The product is:\n";
    //Display matrix result
    for(i=0;i<k;i++)
    {
        for(j=0;j<n;j++)
        {

            cout<<result[i][0];

        }
        for(j=1;j<n;j++)
        {
            cout<<' '<<result[i][j];
        }
        cout << "\n";

    }
}
else
{
    cout<<"The two matrices have incompatible dimensions.\n";
}  

return 0;
}

Sorry for the bad typing!

ZiWei Pan
  • 11
  • 2
  • 5

0 Answers0