Then please tell me what should be the result of this .
#include<iostream>
#include<cstring>
using namespace std ;
int main()
{
char arr[3];
cout<<strlen(arr)<<endl ; // I got 2
cout<<"Insert :" ;
cin>>arr;
cout<<"you inserted: "<<arr<<endl ; // if i entered aaaaaaaaaaaaaa , I will get that prined. I thought that it will print up to 3 characters(aaa). Is my basic theory wrong ?
return 0 ;
}
Yes. You have enough room for a c-string of length 2. (The 3rd element must be a nul character to terminate the c-string.)
On your first strlen: The contents of arr are unspecified. Using strlen here results in undefined behavior -- you know -- the stuff you want to avoid at all costs in a correct program.
You don't limit the number of chars you're extracting from the stream and cin has no way of knowing the size of the storage you're feeding to it, so it doesn't stop at 2 characters if you enter more than 2, so when you do enter more than 2 it results in undefined behavior -- you know -- the stuff you want to avoid at all costs in a correct program.
Your program could blow up your monitor and it would be within the range of undefined behavior. Don't write to or access memory you don't own.
strlen counts caracters until it finds the character with value 0 ('\0'). This has nothing to do with your size of the array. strlen starts at an address in the RAM and counts until it finds 0. 0 isn't included in the count.
Also strcpy, strcat, strcmp work this way, or printf, puts and many other functions more. The end of character strings always is marked by 0 or has to be marked by 0.
I will not repeat what was already said. I only will add that if you would use standard template class std::string you will get the result you were awaiting.:)
to get a input data with array, you can use a function from ctype.h
Example :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include<iostream>
#include<ctype.h>
usingnamespace std ;
int main()
{
char arr[6];
cout<<"Insert :" ;
cin.getline(arr, sizeof(arr)); //a function from library ctype.h
cout<<"you inserted: "<<arr<<endl
system("pause");
}
if i give a sentence whose length exceeds the length of the array, then the sentence will be printed along the size of the array that has been declared.
@anirudh sn and @Hendro P Sinaga
Let me show you this:
1 2 3 4
#include <stdio.h> // C Stdio header
#include <cstdio> // C++ Stdio header
#include <ctype.h> // C Ctype header
#include <cctype> // C++ Ctype header
The C++-Corrected headers are like: "c" + (Name Of C Header) - ".h"
You'll see that, inside these C++-corrected headers, the C headers have been included. Just, DO NOT worry about that. Worry about the fact that you must include the C++-Corrected headers.