-
June 25th, 2009, 11:01 PM
#1
string problems if/else structure
hey guys, this should be an easy one, i'm pretty noobish.
i'm trying to make a simple password-type thingy. all i need it to do is check a string input from the user, and execute code if the string matches what the program knows.
i'm sure you'll get what i'm trying to do with the code:
beginning with all the glory:
Code:
#include "stdafx.h"
#include <iostream>
#include <conio.h>
#include <string>
using namespace std;
Code:
int main()
{
string psd;
cout << "enter password.\n";
getline( cin, psd );
if (psd == "joshua") cout << "it works!";
else cout << "you suck at life.";
_getch() //this is just to save me from it closing out while i debug
return 0;
}
i made another attempt at this same effort, convinced i could never get it right with what i was trying. so i did this:
Code:
int main()
{
char psd[7];
cout << "password?";
cin >> psd;
if (strcmp (psd, "joshua")) cout << "massive win.";
else cout << "epic fail.";
_getch();
return 0;
}
if you couldn't tell, my computer keeps insulting me. can anybody tell me what i'm doing wrong?
i would appreciate it A LOT.
-
June 25th, 2009, 11:20 PM
#2
Re: string problems if/else structure
Originally Posted by teejaytiger
if (strcmp (psd, "joshua")) cout << "massive win.";
else cout << "epic fail.";
[/code]
if you couldn't tell, my computer keeps insulting me. can anybody tell me what i'm doing wrong?
i would appreciate it A LOT.
Hi,
strcmp (psd, "joshua") will return you "0" when both the strings are same, which is FALSE for an "if" i.e. if(0) so it will execute your "else" part. Thats why the result will be vice-versa in your case.
Use if(!strcmp (psd, "joshua"))
Hope this helps,
Thanks,
-
June 26th, 2009, 12:37 AM
#3
Re: string problems if/else structure
haha, thanks. i knew it had to be something simple like that.
thanks a ton!
-
June 26th, 2009, 02:18 AM
#4
Re: string problems if/else structure
Few concerns, that you are not corcerned at this moment...
1. What if password typed by use is more than 7 characters?
2. Your binary (.EXE) may be opened by anyone to find strings, and "joshua" can be detected by attacker!
3. That string may also be changed!
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|