Hi,

I want to count the number of characters of a string. Try to do it as follows.

int iSpace = 0;
	int iLength;

	string strTemp("This is a line                      of text");
	iLength = strTemp.length();

	cout << iLength << endl;

	for(int i = 0; i < iLength; i++)
	{
		if((strTemp.at(i) == ' ') || (strTemp.at(i) == '\t') || (strTemp.at(i) == '\0'))
		{
			iSpace ++;
		}
	}
	printf("\nNumber of characters %d", (iLength - iSpace));

Can you guys comments on my code, either this way is ok or bad attempt

yup...looks fine to me. How about modifies it for user inputs? See if it can manipulate with users' requirements

Dealing with the user inputs wont difficult. Anyway I'll check it. What I'm really worried about is the way I find the characters of the string.

Easy...Try to insert the characters into an array. That way, you can see what contains in it more clearly

Use of an array can be more works. What it the my code odd you can see. Please let me know.

Correction to WolfPack post....

for(int i = 0; i < iLength; i++){
            if(isspace(strTemp.at(i)))
            {
                              iSpace ++;
            }
    }

Thats it...Actually, isspace() returns either 0 or 1. In other words, it gives a false or true. Just like conditions

Still, in a certain conditions, isspace() would produce more dependent ways of producing outputs. Its your program after all ;p

Yep, seems it is more reliable than use of few number of if() conditions. Output also seems much better there. Thanks pal.

The isspace(int ch) function returns nonzero if ch is a whitespace character, including space, horizontal tab, vertical tab, formfeed, carriage return, or newline character; otherwise, zero is returned.

The isspace(int ch) function returns nonzero if ch is a whitespace character, including space, horizontal tab, vertical tab, formfeed, carriage return, or newline character; otherwise, zero is returned.

Yep, I go through the MSDN and found the way it works. Thanks.

This article has been dead for over six months. Start a new discussion instead.