以下代码用于以螺旋顺序打印矩阵的元素。该程序工作正常。然而,问题是我检查程序的测试编译器在输出结束时不接受尾随空格。谁能给我一些关于如何绕过输出中添加的最后一个空格的想法?
#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;
}
抱歉输入不好!