0

I want to output some numbers, all separated with a comma. In the following code also the last number will be "separated":

for(int i=1; i<=3; i++)
{
   cout << i << ",";         
}

Is it possible to avoid that?

So instead of 1,2,3, I want just 1,2,3

4

4 回答 4

4

You have to put comma in diffrent place, like this:

const int n = 5;
int tab[n] = {1,2,3,4,5};

if(n >= 1) 
    cout << tab[0];
for(int i=1; i<n; i++)
    cout<<", "<<tab[i];

Link to ideone.com, where code can be executed.

于 2013-04-22T21:46:08.633 回答
2

This is what I tend to do in such cases:

for (int i = 1; i <= 3; i++) {
    if (i > 1) cout << ", ";
    cout << i;
}
于 2013-04-22T21:44:57.733 回答
0

You will probably have to write the last (or first) number by itself:

int i;
for (i = 1; i < 3; i++)
{
    cout << i << ",";
}
cout << i << endl;
于 2013-04-22T21:44:46.537 回答
-2

Your loop runs three times. If you write a comma every time, you're gonna get three commas. If you don't want the last comma, you can just use an if statement to not write it. Your loop could be:

cout << i;
if(i < 3)
cout << ",";
于 2013-04-22T21:46:07.027 回答