Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

c++ - For loop prints an extra comma

cout<<"Set B : {";
for(i=0;i<b;i++)
{
    cout<<setB[i];
    cout<<",";
}
cout<<" }"<<endl;

The code above is not printing right. It should print Set B : {1,2,3} but it prints an extra comma ==> Set B : {1,2,3,}

Any help would be appreciated. Thanks in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use

cout << "Set B : {";

for (i = 0; i < b; ++i) {
  if (i > 0) cout << ",";

  cout << setB[i];
}

cout << " }" << endl;

I changed your algorithm :

Before it meant : "Put the number and then put a comma"

Now it means : "If there is a number behind me put a comma, then put the number"

Before, you always printed a comma when you printed a number so you had an extra comma.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...