removing last written symbol from stream

D

Denis Petronenko

Hello,

for(int i=0; i<100; ++i){
cout << i << ",";
}
// how can i remove last comma here?
......
cout << endl;
 
M

mlimber

Denis said:
Hello,

for(int i=0; i<100; ++i){
cout << i << ",";
}
// how can i remove last comma here?
.....
cout << endl;

Use an if statement in the for-loop. If you're on the last iteration,
don't print one.

Cheers! --M
 
D

Denis Petronenko

mlimber said:
Use an if statement in the for-loop. If you're on the last iteration,
don't print one.

Cheers! --M

ok. lets see on following example.

i want to print elements of set divided by comma:

set<int> myset;
for(int i=0; i<10; ++i) myset.insert(random());
for_each(myset.begin(),myset.end(),printint());

i defined function object to do this job:

class printint
{
public:
printint(){}
~printint(){
// remove last comma here
cout << endl;
}

void operator()(int val){
cout << val << ",";
}
};

How can i remove or not write last comma here? function object don't
know how many elements stored in myset.

Thanks.
 
D

Daniel T.

"Denis Petronenko said:
Hello,

for(int i=0; i<100; ++i){
cout << i << ",";
}
// how can i remove last comma here?
.....
cout << endl;

Don't put it in in the first place.

for ( int i = 0; i < 99; ++i )
cout << i << ',';
cout << 99 << endl;
 
M

mlimber

Denis said:
ok. lets see on following example.

i want to print elements of set divided by comma:

set<int> myset;
for(int i=0; i<10; ++i) myset.insert(random());
for_each(myset.begin(),myset.end(),printint());

i defined function object to do this job:

class printint
{
public:
printint(){}
~printint(){
// remove last comma here
cout << endl;
}

void operator()(int val){
cout << val << ",";
}
};

How can i remove or not write last comma here? function object don't
know how many elements stored in myset.

Thanks.

You either need to find some other way to do it, or you need to make
the functor stateful (e.g., have it keep its own count and pass the
upper limit in via the constructor).

Cheers! --M
 
?

=?ISO-8859-15?Q?Juli=E1n?= Albo

Denis said:
i defined function object to do this job:

class printint
{
public:
printint(){}
~printint(){
// remove last comma here
cout << endl;
}

void operator()(int val){
cout << val << ",";
}
};

How can i remove or not write last comma here? function object don't
know how many elements stored in myset.

But it can know when it's first called. So you can supress the first instead
of the last.

if (first)
first= false;
else
cout << ",";
cout << val;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,682
Members
48,796
Latest member
Greg L.

Latest Threads

Top