Trouble understanding "char(tolower(ch))"

Hey guys. My friend sent me this code...

Maybe it's because i'm tierd, or maybe because i'm newbie (probably the latter), but I've trouble understanding this code, specifically "char(tolower(ch))"... What's happening right there? and why do I have to type "char", why not just "(tolower(ch))" alone?

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
#include "stdafx.h"
#include <iostream>
#include <cctype>

int _tmain(int argc, _TCHAR* argv[])
{
	using namespace std;
	char ch;
	
	cout << "Type whatever you want... [Type @ to quit the program] :" << endl;
	
	
	while (cin.get(ch) && ch != '@')						
	{
		
		if (isdigit(ch))
			continue;						
		if (isalpha(ch))
			if (isupper(ch))
				cout << char(tolower(ch)); // <-- these two
			else
				cout << char(toupper(ch)); // <--
		else
		        cout << ch;			
	}
	return 0;	
}


Thanks in advance!
Last edited on
The character variable type in C++ can easily convert between integer and character representation.
http://www.cplusplus.com/reference/cctype/tolower/
This links to a nice explanation of tolower. The most important thing to notice pertaining to your question is the function's prototypes:
int tolower ( int c );
You will notice the function takes an integer as input and returns an integer as output.
Inside the tolower function call there is no need to cast the character variable to an integer because that code is automatically generated by the compiler. You do have to cast the returned integer to a character when the compiler can't explicitly tell what you mean. The standard out can take all kinds of different variable types including integers. Since that is what tolower returns, cout thinks you want to print the integer out to the screen. Casting it to an integer explicitly tells the compiler that you would like for it to be a character instead.
Last edited on
Alright, I got it now. Thank you for the fast and clear explanation! :)
Topic archived. No new replies allowed.