Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I'm Confused! Char, Char* or String in C++

Tags:

c++

c-strings

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.

like image 953
Suchal Avatar asked Jun 19 '12 16:06

Suchal


1 Answers

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 chars, 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 chars (namely, 5 chars, 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.

like image 110
GILGAMESH Avatar answered Sep 22 '22 07:09

GILGAMESH