PDA

View Full Version : declared one varibale char s1[10] but when i am inputing the string



sana.pari
04-24-2011, 02:11 AM
i declared one varibale char s1[10] but when i am inputing the string, it is accepting more than 9 characters. why it is like this? i have put different number in the bracket but there when i am puting the sting, there is no setriction. how the other characters are accepting and where are they going for save?



Thank you so much

Xpert
04-24-2011, 02:11 AM
You are facing this problem becuase you are trying to overflow the buffer. When we print the array value using cin statement, cin reads a character array until the user presses the enter key. When enter key is pressed, cin takes the whole input (i.e. string) and stores it into the array name. Remember that if we put a string larger than the size of the array in absence of a null character in it, then it is not possible to determine where a string is terminated in the memory. This can cause severe logical error. So, one should be careful while declaring a character array. The size of array should be one more than the number of characters you want to store. To handle such issues, always use loop to print the character string stored in array. Below is the code which will help you understand the problem.

#include <iostream.h>
#include<conio.h> main()
{
char s1[10];

cout<<"Enter your name:\t";
cin>>s1;

for ( int i = 0 ; i < 10; i ++ )
cout<<s1[i];


getch();
system("pause");
}


Here in the above code, for loop is used to print the character array. Here the purpose of the for is to print the value of the array upto its upper limit and it will discard the remaining character which are stored beyond the character array limit.