conversion argv[] to char

i was just trying to make a test program that can accept parameters in main() but there's something weird when i tried to enter a character. so i wanna see the output of the entered character, thus, i tested it this way:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <string>
#include <cmath>

int main (int argc, char* argv[]) {
	if (argc > 1) {
		std::cout << (char)argv[1] << std::endl;
	}
	std::cin.clear();
	std::cout << "press ENTER to close program.";
	std::cin.get();
	return 0;
}


and when i entered it like this:

test_cpp *


the result is:
5
press ENTER to close program.


also, it varies as follows:

test_cpp +
ì
press ENTER to close program.


test_cpp +
§
press ENTER to close program.


why is it happened that way?
argv[1] is a pointer to a null-terminated string; char* argv[] is an array of pointers.

Even if the argument appears to be a single character, it really would be the first character of a null-terminated string; argv[1] would point to it.

Print out argv[1] as it is; do not cast the pointer to char.

1
2
// std::cout << (char)argv[1] << std::endl;
std::cout << argv[1] << '\n' ;
@JLBorg: ok. but what i mean is, what happened inside the program when it tried to convert argv to char
chipp wrote:
ok. but what i mean is, what happened inside the program when it tried to convert argv to char


Nowhere in your program do you try to convert argv to char.

At line 7, you try to convert argv[1] to a char. That is a different thing, and it's important to understand that.

What happens is:

- argv[1] is a char*, i.e. it is a pointer, i.e. it is an integer. Any pointer is just an integer, and the value of that integer is interpreted as a memory address.

- we convert that integer to a char. A char is also an integer, but only an 8-bit one, that can hold a value in the range 0 - 255. The value is interpreted as an ASCII code representing a single character. So, the integer that is potentially bigger than 255, is truncated to a value that can fit into an 8-bit integer, from 0 - 255.

- when that integer value is output using cout, it is inerpreted as an ASCII code. The character that is shown on your screen is the character represented by that code.
> what happened inside the program when it tried to convert argv to char

There is no real conversion;
with the cast, the program just demands that the compiler treat argv[1] as if it were an object of type char

argv[1] is a pointer; the value that it contains an address. (char)argv[1] treats the first byte of that address as an object of type char. What character is printed out when we try to print out that first byte as if it were a char depends on the address that the pointer happens to hold.

@mikey: ah i see...! thanks for the explanation! i forgot that part!!
You're welcome - glad I could help!
Topic archived. No new replies allowed.