Removing Last Character in String

Hello all,

I have a bit of an issue with a function. Everything works fine, I did the program, and all that good stuff. So, now I want to make it look pretty before I hand it in.

Here's the function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
string perf (int x) {

int y;
bool u;
stringstream ss;
string butt;

y = 0;

for (int g = 1; g < x; g++) {

	if ((x%g) == 0) {
	y += g;
	ss << g << '+'; }
	else ;
	
	}

ss << "\b\b"; // This is where I'm having the problem

if (y == x)
	ss << endl << "Yes, " << x << " is a perfect number." << endl;
else
	ss << endl << "No, " << x << " is not a perfect number." << endl;

butt = ss.str();
return butt;
}


So, yes. Basically, when it outputs the string, it's giving me an extra plus at the end of the output, looking like this:

Welcome to Perfect Number v. 1.3.

Please make your selection from the choices below: 
(1) Identify whether a single integer is a perfect number or not.
(2) Display a range of integers, showing all perfect ones.
Make your choice: 1
Enter an integer, and I will tell you if it is a perfect number: 26

1+2+13+
No, 26 is not a perfect number.
Would you like to try another number? Y/N? 
n


So, my question is- what is the command to remove the LAST character from a string. And yes, I did Google for it, and the problem is, most of those answers require the knowledge of the position of the character you want to delete, whereas my position always changes.

If you can tell me what to search for, that would be nice as well.
Last edited on
substr: http://cplusplus.com/reference/string/string/substr/

1
2
butt = ss.str();
return butt.substr(0, butt.length() - 1);


Of course another idea would be to not add that extra + in the first place.
1
2
3
butt = ss.str();
butt.erase( butt.size() - 1 );
return butt;
OMG Thank you so much! It's just that we just started covering strings, and didn't get to substrings yet. But thank you so much nonetheless!
Topic archived. No new replies allowed.