0
What is the problem with this program ..loop never ends even if i enter right password
#include<iostream> #include<string> using namespace std; int main() { do { cout<<"enter password"; string userPassword; cin.ignore(); getline(cin,userPassword , '/n'); if(userPassword=="teddy") { break; } } while(true); return 0; }
7 Answers
+ 5
There is no need for strcmp. You are using a string, it can compare with a const char* just fine using ==. No address comparison is done here.
The issue is that cin.ignore() asks for input because the input stream is empty( there is nothing to ignore ).
You may think it's the getline that's asking the input but that's not the case.
After input cin.ignore then proceeds to ignore 1 character, if the input is "teddy" the 't' is ignored.
"eddy" is now left in the input stream.
Now getline reads from the input stream, since it's not empty it doesn't ask you for input, now userPassword contains "eddy".
"eddy" is not equal to "teddy".
If the user would enter "tteddy", userPassword would contain "teddy".
So, remove the cin.ignore line, it's not needed here.
Also '/n' should be '\n', or just remove that, it's a default parameter anyway. Well technically it's input.widen('\n'), but its close enough.
+ 1
you should use strcmp to compare two strings. if not, you are comparing their addresses.
you can test this doing
printf("%p %p\n", userPassword, "teddy");
and seeing they are not equal.
+ 1
is strcmp a headerđ
đ
+ 1
strcmp(str1, str2) tells you the number of different characters. if it is 0 they are equal
0
it is contained in string.h
0
how can i use strcmp... syntax.. or example that can help me to understand
0
thanks roja and dennis for help.... ââ