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; }

22nd Aug 2018, 2:08 PM
Teddy
Teddy - avatar
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.
22nd Aug 2018, 3:07 PM
Dennis
Dennis - avatar
+ 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.
22nd Aug 2018, 2:30 PM
Bebida Roja
Bebida Roja - avatar
+ 1
is strcmp a header😅😅
22nd Aug 2018, 2:35 PM
Teddy
Teddy - avatar
+ 1
strcmp(str1, str2) tells you the number of different characters. if it is 0 they are equal
22nd Aug 2018, 3:00 PM
Bebida Roja
Bebida Roja - avatar
0
it is contained in string.h
22nd Aug 2018, 2:35 PM
Bebida Roja
Bebida Roja - avatar
0
how can i use strcmp... syntax.. or example that can help me to understand
22nd Aug 2018, 2:36 PM
Teddy
Teddy - avatar
0
thanks roja and dennis for help.... ✌✌
22nd Aug 2018, 3:10 PM
Teddy
Teddy - avatar