Sunday, 8 September 2013

What is the limitation of cin while taking input for character array

Tags

What is the limitation of cin while taking input for character array?

Ans: 


To understand this consider following statements, 

                             char str[5] ;
                             cin >> str ; 


While entering the value for str if we enter more than 5 characters then there is no provision in
 cin to check the array bounds. If the array overflows, it may be dangerous. This can be  avoided by using get( ) function. For example, consider following statement, 

                             cin.get ( str, 5 ) ;

On executing this statement if we enter more than 5 characters, then get( ) takes only first five characters and ignores rest of the characters. Some more variations of get( ) are available, such as shown below:

                             get ( ch ) - Extracts one character only

                             get ( str, n ) - Extracts up to n characters into str

                             get ( str, DELIM ) - Extracts characters into array str until specified delimiter (such as '\n'). Leaves delimiting character in stream.

                             get ( str, n, DELIM ) - Extracts characters into array str until n characters or DELIM character, leaving delimiting character in stream.


EmoticonEmoticon