2014-02-18 113 views
1

我正在編寫一個程序,並且必須檢查用戶輸入的字符是否等於數組中的某個字符。如果它不等於任何它應該顯示「無效....」。它不適合我,任何人都可以向我解釋我做錯了什麼。每次我都會收到無效的字符。C++檢查數據是否相等

我有一個char數組data [5];該賣場5個字母

cout<<"Enter one character to delete: "; 
cin>>del; 


cout<<del; 
for(int x=0;x<4;x++) 
    { 
     if(del!=data[x]) 
     { 
     cout<<"Invalid, character not entered.\n"; 
     break; 
     } 

    } 
+0

如果'del'不等於'數據[ 0]','break'語句將帶你離開for循環(不用嘗試x的其他值)。 – nonexplosive

+0

我建議使用'std :: string'和'std :: string :: find'(和'std :: string :: erase'來刪除一個)。 – chris

回答

4
for(int x=0;x<5;x++) 
{ 
    if(del==data[x]) 
    { 
    cout<<"Character found at " << x << endl; 
    break; 
    } 

} if(x==5) cout<<"Character not found" << endl; 
0

如果你的字符數組是一個C風格空結尾的字符串,那麼你可以使用,和strchr:

#include <cstring> 
//... 
if (strchr(data, del)) { 
    // character found 
} 
else { 
    // character not found 
}