Replacing white spaces in a string

Hi,

I have the following string:

string a = {12 450 000 EUR, 13 452 700 USD, 34 500 CHF}

and the following code:

1
2
3
4
5
6
7
8
9
10
11
	
string str (" ");

for (i=0; i<number_of_trades; i++)
	{
		a[i].replace(a[i].find(str),str.length(),"");

		cout << a[i];
		Sleep(1000);

	}


that yields:

string a = {12450 000 EUR, 13452 700 USD, 34500 CHF}

But there are still whitespaces, so I try:

1
2
3
4
5
6
7
8
9
10
11
	
string str (" ");

for (i=0; i<number_of_trades; i++)
	{
		a[i].replace(a[i].find(str),str.length(),"");
a[i].replace(a[i].find(str),str.length(),"");
		cout << a[i];
		Sleep(1000);

	}


and I get an error...

If somone would care tell me why this doesn't work, how to fix it, and if there is a less code heavy alternative.

Thanks


and I get an error...
What kind of error?

replace() replaces the part of the string at the given position and size once. you need a loop:
1
2
3
4
5
6
7
8
std::string::size_type found; // EDIT: I knew there was an typo...
do
{
  found = a[i].find(str);
  if(found != std::string::npos)
    a[i].erase(found, str.size()); // I this case erase suffice
}
while(found != std::string::npos);
Last edited on
Nevermind, looks like it works well.

Thx for your time.

This is the error I have using my first code:

Unhandled exception at 0x7608b760 in PL calculation.exe: Microsoft C++ exception: std::out_of_range at memory location 0x001826bc.

have any idea what it is about ?

---

EDIT: the problem was when the string had no spaces.
Last edited on
Nevermind, looks like it works well.
What?


the problem was when the string had no spaces.
Yes. find() returns and invalid number(-1) if it doesn't find the requested string and replace() complains about that invalid value. Therefore I introduced if(found != std::string::npos) // npos is an invalid value
Topic archived. No new replies allowed.