char Name[6]; How much characters can a user input? Would there be a null-terminator at 5th index?

char Name[6];


How much characters can a user input? Would there be a null-terminator at 5th index?

How much characters can a user input?


As many as they like, but you have only set aside space for 6 characters; if you want this to be a C-string, 5 characters and a null terminator.

Would there be a null-terminator at 5th index?

Only if you put it there yourself. It's not a C-string until you put the null terminator on, so don't go using it with functions that expect C-strings.
Last edited on
So, this thing is a C-string, right?

char Name[]="james";

and it is equivalent to writing char Name[]={'j','a','m','e','s','/0'};

Right?
Almost. You have the right idea, but the null character is '\0' (or just 0), not '/0'. So it would be the same as this:

 
char Name[] = {'j','a','m','e','s',0};

How much characters can a user input? Would there be a null-terminator at 5th index?


If you use the library function getline for input to an array of characters the terminating null is automatically added at the end.

istream& istream::getline( char* str, streamsize count )

This will read everything up to and including the newline character, but will only store at most count - 1 characters and then add the terminating null. The newline character, although read from input, is not stored. If you attempt to read more than count - 1 characters the excess characters are discarded and not stored and the failbit on the stream is set.

In your example you could use:

getline( Name, 6 );

If you type in "Joe" then you would have Name = { 'J', 'o', 'e', '\0', '?', '?' }

If you type in "James" then you would have Name = { 'J', 'a', 'm', 'e', 's', '\0' }

If you type in "Joseph" then you would have Name = { 'J', 'o', 's', 'e', 'p', '\0' } with the final 'h' in "Joseph" dropped and the failbit of the stream set.
Topic archived. No new replies allowed.