2014-02-20 107 views
1

我是C++新手。 所以我做了這個程序,應該是一個密碼thingy。 問題是,當我輸入正確的密碼,即「bobby」時,它會直接轉到其他而不是如果C++ if語句

什麼問題?

我的代碼:

#include <iostream> 
using namespace std; 

int main() 
{ 
char password[] = "bobby"; 
char passinput[50]; 
char num[50]; 

top: 
cout << "Please enter your password: " << endl; 
cin >> passinput; 
if(passinput==password) 
{ 
    cout << "Correct" << endl; 
    cin >> num; 
} 
else 
{ 
    cout << "Incorrect, try again" << endl; 
    goto top; 
} 
} 
+0

http://www.cplusplus.com/reference/string/string/compare/ –

+6

'goto' [認爲是有害的(http://en.wikipedia.org/維基/ Considered_harmful)。不要使用它。 – Maroun

+1

@MarounMaroun:「認爲有害」的散文[認爲有害](http://meyerweb.com/eric/comment/chech.html)。但是,是的,你很少想要「goto」,而你當然不想在這裏。 –

回答

4

if(passinput==password)只是兩個字符串的起始地址進行比較。由於兩個字符串位於不同位置,因此條件passinput==password評估爲false,並且您的if正文未執行。
要比較兩個c風格的字符串,可以使用<string.h>中的srtcmp標準庫函數。

if(!strcmp(passinput,password)) //strcmp returns 0 if strings are equal. ! is used to make that 0 (false) to 1 (true) 
{ 
    cout << "Correct" << endl; 
    cin >> num; 
} 
+0

啊,好吧,但我該如何使用srtcmp?我該怎麼辦? – user3333421

+0

更新了我的答案。 – haccks

+0

@EricLippert這樣的評論最好伴隨着[此鏈接](http://stackoverflow.com/q/388242/1782465)。 – Angew

6

使用strcmp比較C風格字符串
或者使用std::string代替,因爲您標記的問題C++:

string password("bobby"); 
string passinput; 
string num; 
+1

+1推薦'std :: string'。計算char *'在學習過程中的某個時刻是如何工作的,但在C++中你幾乎不會使用它。 – CompuChip

+1

雖然這可能是一個明智的建議,但它並沒有真正回答這個問題,這就是爲什麼代碼不起作用 – mjs

2

使用string::compare或比較的C++字符串中的平等,只有當==,否則你只是比較兩個C風格字符串的地址。

要做到這一點在C++中,使用

std::string password; 
std::string passinput; 
std::string num; 

// if(password.compare(passinput) == 0) also would work 
// but as noted in the comments, is overkill for what you 
// are doing 
if (password == passinput) 
{ 
    cout << "Correct" << endl; 
    cin >> num; 
} 
else 
{ 
    cout << "Incorrect, try again" << endl; 
    goto top; 
} 

在C做到這一點(這是您當前使用的字符串的風格),見@haccks答案。爲了方便起見,我添加了他的答案的部分,描述瞭如何在下面做到這一點。

要比較兩個C風格的字符串,你可以使用srtcmp標準庫函數。

// strcmp(passinput, password) returns 0 for 
// a successful match. The ! (negation) 
// converts 0 (false in c) to true 
if(!strcmp(passinput,password)) 
{ 
    cout << "Correct" << endl; 
    cin >> num; 
} 
+3

std :: string對於相等運算符有一個有效的重載== – MatthiasB

+0

string :: compare是過度的if你不關心哪個字符串是'更小'。 – tgmath

+0

使用'.compare'並不正確,但我同意,在這種情況下不需要。我修改了我的答案以反映這一點。 –

0

嘗試:

if (strcmp (passinput,password) ==0) 
{ 
... 
} 

的strcmp返回0,如果字符串是一樣的,一個值大於零,當不匹配在第一串比第二字符串和一個大的值的第一個字符價值低於零其相反。

包括:字符串/ string.h中