AlexDan
AlexDan

Reputation: 3351

using cin.get() function

char arr[100];
cin.get(arr,100);
  1. Is this safe? Will the null-character be appended at the end even if I type more than 100 chars? or should I use cin.get(arr,99)?
  2. When I type ENTER, is the end-of-line character part of the array or not?

Upvotes: 0

Views: 15880

Answers (2)

Jesse Good
Jesse Good

Reputation: 52395

1)is this safe. I mean will the null-character be appended at the end. even if I typed more than 100 chars. or it must be cin.get(arr,99).

Taken from here.

The signature of get you are using looks like this:

basic_istream& get( char_type* s, std::streamsize count );

It will read at most count - 1 characters from the stream (in your case 99) or up until the delimiting character, which is by default \n. So if you type more than 100 characters, a call to get will read 99 of those characters and then append the null terminator \0 at the end.

2)also when I type ENTER, a newline get passed. so does this character is really a part of the array or not.

No, get read up until the delimiting character, so if you press ENTER, \n will be left in the stream as the next character to be read.

Advice: Please use the site I linked to in order to understand how these functions work, and prefer std::string and std::getline if you are coding in C++.

Upvotes: 1

dreamlax
dreamlax

Reputation: 95405

The answers to both of your questions can be found here, but to reiterate:

  1. The get method reads at most n - 1 characters. This means that the method expects the size of the buffer and not the number of characters to read. This method automatically appends a null character to the end.

  2. The newline character is not extracted or stored in the array.

You may also want to consider using std::getline which you can use in conjunction with std::string.

Upvotes: 2

Related Questions