Nov 15, 2013 at 2:59pm Nov 15, 2013 at 2:59pm UTC
Simple program that asks for my name then returns name, but instead of full name i only get the first character of the name.
1 2 3 4 5 6 7 8 9 10 11 12
#include <iostream>
using namespace std;
int main()
{
char myName ;
cout << "Hello, what is your name?\n" ;
cin >> myName ;
cout << "Hello " << myName << "\n" ;
}
Where am I doing a mistake?
Edit: Just realised changing myName from char to string and including <string> solved my problem. Is char only supposed to be one character?
Last edited on Nov 15, 2013 at 3:07pm Nov 15, 2013 at 3:07pm UTC
Nov 15, 2013 at 3:06pm Nov 15, 2013 at 3:06pm UTC
Your mistake:
char myName ;
It should be
char myName[CHAR_ARRAY_SIZE_GOES_HERE] ;
Last edited on Nov 15, 2013 at 3:06pm Nov 15, 2013 at 3:06pm UTC
Nov 15, 2013 at 3:07pm Nov 15, 2013 at 3:07pm UTC
So the default array size for char is one?
Nov 15, 2013 at 3:09pm Nov 15, 2013 at 3:09pm UTC
No. char
is not an array. char
is a single character.
There is no default size for an array. When you create an array, you have to specify the size.
Last edited on Nov 15, 2013 at 3:10pm Nov 15, 2013 at 3:10pm UTC
Nov 15, 2013 at 3:11pm Nov 15, 2013 at 3:11pm UTC
char myName ;
This just declares a character variable. If you want to declare an array, you'll have to use square braces immediately after the identifier and specify the number of elements in it. There is no defualt size in an array.
http://www.cplusplus.com/doc/tutorial/arrays/
Last edited on Nov 15, 2013 at 3:12pm Nov 15, 2013 at 3:12pm UTC
Nov 15, 2013 at 3:13pm Nov 15, 2013 at 3:13pm UTC
Yes, that's what I said. The default array size for char is then a single character. If however I change the array size with [] to [10] the size of the elements become 10 instead of a single character. Right?
Edit: [10] would make the elemenets 11 not 10.
Last edited on Nov 15, 2013 at 3:14pm Nov 15, 2013 at 3:14pm UTC
Nov 15, 2013 at 3:14pm Nov 15, 2013 at 3:14pm UTC
The default array size for char is then a single character.
NO!
char
is not an array . If you write:
char myName ;
then there's no default array size of 1, because
there is no array of any kind there!
Last edited on Nov 15, 2013 at 3:15pm Nov 15, 2013 at 3:15pm UTC
Nov 15, 2013 at 3:15pm Nov 15, 2013 at 3:15pm UTC
char myName[];
will give an error. And I tell you again there's no default array size. char myName ;
is a variable declaration, not an array declaration.
Nov 15, 2013 at 3:15pm Nov 15, 2013 at 3:15pm UTC
Sorry after looking up what an array is I now understand.
Thank you very much!