How to read trailing spaces in a string?

Hi,

My program below does not count the 3 trailing spaces in " Hi There "; it takes only the first two and the one between Hi and there.

Can you please help?

Thanks a lot,
Suresh

==================================================================================

# include <iostream>
# include <string>
using namespace std;

int main()

{

string line=" Hi there ";
int charcount = 0;
int spacecount =0;


charcount = line.length();
cout << "The string entered is : " << line << endl << endl;
cout << "The length of the string is : " << charcount<< endl;

cout << line [0];

for (int i=0; i< charcount; i++)

{
if (line[i] == ' ')

{
spacecount ++;
charcount --;
}


}

cout << "The number of spaces in the entered string is: " << spacecount << endl;

cout << "The number of charecters in the entered string is: " << charcount << endl;
return 0;
}
1
2
3
4
5
6
7
8
	for(int i = 0; i < charcount; i++)
	{
		if(line[i] == ' ')
		{
			spacecount++;
			charcount--; // Why are you doing this?
		}
	}
To find the number of charecters in a string excluding the white spaces. May be I should use a different variable for that? As it is interfering with the "for" loop?

I tried it and it works!

Thanks a ton.
Topic archived. No new replies allowed.