Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

confusion in strlen behaviour

0 votes
asked Apr 16, 2020 by AmoghaKS (250 points)
Please follow this link..I have commented my doubts in the program


using character array & providing input as "kjlp" where I expect the output of strlen of array to be 4; but in some cases it is different which outputs 6. Why so??

1 Answer

+1 vote
answered Apr 19, 2020 by Manuel Mateo (1,190 points)
selected Apr 22, 2020 by AmoghaKS
Best answer

So, what you did is you misused cin.get(). You tried to ser a[0] = cin.get(), but the proper way is to actually do it how I did in the link https://onlinegdb.com/SyJ-8ecOL.

commented Apr 21, 2020 by AmoghaKS (250 points)
Thank you very much, now I understood the code that you've written and the right way of using it.

please clarify this too.
a[0] = cin.get() //this can be used to read single character right....is there any other disadvantages of using cin.get() like this.

and what is the actual reason for that behavior in my code??
is it something related to compiler or with memory, the way how it is stored or what exactly happened over there?
commented Apr 22, 2020 by Manuel Mateo (1,190 points)
So, cin.get(string name, size) is a way to get the user input with whitespace. Basically an entire word or phrase instead of just a single string. If you want to read a character from an array or string, you simple do std::cout<<a[i]; where i is the index number of the character you want to read.

The issue in your code lies in a misunderstanding of syntax. cin.get() is to put user input into the string you define in its arguments, not to read a specific letter. If you look back at the code, I simply do

cin.get(a, 80)

which tells the program to get the user input, and put it into the array a, with a maximum size of 80. There are no extra steps to add.
commented Apr 23, 2020 by Umair Abbas (100 points)
u can simply store strlen in a variable and after users input u should cout variable to get length of desired array.

char arr[10];
int length=strlen(arr,10);
cout <<"lenght is: "<<length<<endl;
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.