在打印列表中的最后一项之后不要包含逗号

时间:2013-10-17 03:41:35

标签: c++

我有一个打印的数字列表:

1:1,
2:1,2,
3:1,3,

如何在每行上不包含最后一个逗号?

for ( int i = 1; i <= x; ++i )
  {
    cout << i << ": ";
    for ( int j = 1; j <= i; ++j )
    {
      if ( i % j == 0 )
      {
        cout << j << ", ";
      }
    }
    cout << endl;
  }

4 个答案:

答案 0 :(得分:2)

试试这个:

for ( int i = 1; i <= x; ++i )
{
cout << i << ": ";
for ( int j = 1; j <= i; ++j )
{
  if (i==j) {
      cout << j;      
   } else if ( i % j == 0 ) {
       cout << j << ", ";
  }
}
cout << endl;
}

答案 1 :(得分:1)

尝试检查数字是否是最后一个,如:

for (int i = 1; i <= x; i++)
{
    cout << i << ": ";
    for (int j = 1; j <= i; j++)
        if (!(i % j))
        {
            if (j != i)
                cout << j << ", ";
            else
                cout << j << endl;
        }
}

答案 2 :(得分:0)

for ( int i = 1; i <= x; ++i )
{
    cout << i << ": ";
    for ( int j = 1; j <= i; ++j )
    {
        if ( i % j == 0 )
        {
            cout << j;
            if (i != j) {
                cout << ", ";
            }
        } 
    }
    cout << endl;
}

答案 3 :(得分:0)

由于您始终输出1,因此请在2

处开始检查
for ( int i = 1; i <= x; ++i )
{
   cout << i << ": 1";
   for ( int j = 2; j <= i; ++j )
   {
        if ( i % j == 0 )
        {
             cout << ", " << j;
        }
   }
   cout << endl;
}

或者,您可以使用分隔符

for ( int i = 1; i <= x; ++i )
{
   char sep = ':'
   cout << i;
   for ( int j = 1; j <= i; ++j )
   {
        if ( i % j == 0 )
        {
             cout << sep << " " << j;
             sep = ',';
        }
   }
   cout << endl;
}