The Epic starting program for every programming language ;) and hi frnds, this is my first post in this forum... nw coming to the matter, i read in many places gets() is EVIL and use cin.getline() instead of it... i actually like prefer cin.getline() over gets() as i know the problem with gets()... but this program gives the contrary...
int strlen(char*); //Am trying to re-create strlen() on my own!
void main () //Turbo-c++
for( ; ; ) //For program repetition...
cout<<"Enter a string : ";
cout<<"No. of characters : "<<strlen(s1);
cout<<endl<<"Do you want to continue? (y/n) : ";
elseif(ch=='Y'||ch=='y') //Actually not required... :P
for(int i=0; ;i++)
Sorry for the big prog guys but its big only cause of the repetition... now the problem is, when i first execute program, it alright... but for the second time..
Enter a string : asd
Do you want to continue? (y/n) : y
Enter a string : 0
Do you want to continue? (y/n) :
Actually i didnt enter any string!!! i didnt enter the 0! i just entered y and the comp entered the remaining things(please try urselves and u will see the o/p)...WHY the hell cin.getline failed to get the input string from the user and from where that 0 came from?!?! :O
Now the best part is, using gets(s1) instead of cion.getline(s1,50) yields the correct O/P!!!! Try and see guys! gets() serves its function here whereas cin.getline becomes evil! WHY?!?!?! PLEASE EXPLAIN! Am beginner, so please give your answers in detail... Actually am a 11th standard student studying c++ in skul :P please go easy on me guys!
You must bring cin.ignore(); or cin.clear(); or cin.sync(); after declaring s1. What it does is to clear the buffer. This is needed because, getline() accepts characters until a newline character('\n') is "seen", and this newline character might have been left in the buffer when the user hit the enter(return) key.
thanx for ur replies guys... but how to get the work done with cin.ignore() or cin.clear()? just call tat function without any parameters?
OH! ya it worked! thanx samrux and Aceix :) now the next question is... Why cin.getline needs this extra function and why doesnt gets() needs it?
getline doesn't need this extra function. You do, because you're mixing line-oriented input with single character extraction. The only reason gets works is because you were also mixing C and C++ input methods and it only works by happenstance. If you were using all C methods, gets would have the same issue.