when i use char or char*, visual studio 2012(11) only couts last character such as:
#include <iostream>
#include <string>
int main(){
using namespace std;
char chName = 'Alex';
cout<<chName;
}
It displays only "x". it is correct is i use
string strName = "Alex"
but in those function which have parameter as a char, string can not be passed on as argument. in this case, VS compiler says that strings cant be converted into int.
also tell me what is difference between char and char*.
I am a PHP developer and C++ is so confusing. Please help me.
char
can only keep 1 character at a time; in this case, it keeps your last character, 'x'
.
char *
is a pointer to one or more char
objects, and if read correctly, can also be used as a string. So setting
const char *chName = "Alex";
cout << chName;
should output the whole name.
Another problem is your use of quotations. 'x'
denotes a char
, while "x"
denotes a array of char
s, known as a string literal.
If there is a function that requires you to pass a char *, you could pass
const char *param = "this is da parameter";
function (param);
or
std::string param = "da parameter"; //std::string is a type of string as well.
function (param.c_str ());
You could also use the declaration
char chName[] = "Alex";
This would create an local array of char
s (namely, 5 char
s, because it appends a null character at the end of the array). So, calling chName[3]
should return 'x'
. This can also be streamed to cout
like the others
cout << chName;
EDIT: By the way, you should return an int
in your function main ()
. Like 0
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With