2015-11-29 44 views
-1

程序會要求用戶輸入只能由ABCD組成的鏈,如果輸入包含除ABCD以外的字母,則必須顯示錯誤,否則應輸出「ok!」。如何檢查字符串中的每個字符?

string strand1; 
again: 
cout << "Enter String 1:\n"; 
cin >> strand1; 
for (int i = 0; i <= strand1.length(); i++) 
{ 
    if (strand1.at(i) != 'A'&&strand1.at(i) != 'B'&&strand1.at(i) != 'C'&&strand1.at(i) != 'D') 
    { 

     cout << "Invalid Input"; 
     system("cls"); 
     goto again; 

    } 
    else 
    { 
     i++; 
    } 
} 
cout << "ok"; 
_getch(); 
return 0; 
+1

你正在增加我兩次。 –

+0

......不要在循環中使用goto;只是不。這就是說我認爲你一直都沒有想到你的解決方案。當你設計你的代碼時,儘量編寫代碼,就像你在紙上處理它一樣。最後,學習你的循環以及如何操作它們以避免使用GOTO。 Goto是99.99%的案例中撒旦的邪惡產物。在其他情況下,加速程序並且無法避免是必要的罪惡。它仍然很邪惡。 – soulsabr

回答

1

你的問題還不清楚,但檢查你的代碼後,我相信問題是,你的循環條件你使用i <= strand1.length時,你應該使用i < strand1.length。 您正在使用的循環條件將檢查索引超出字符串的範圍。另外,你不應該像在for語句中那樣在else語句中增加我。將來,請清楚地說明您的問題以及您收到的任何錯誤代碼。

2
  1. 將必要的檢查移至功能 - isValidInput
  2. 使用手動編碼的邏輯來檢查輸入是否有效,或使用標準庫函數std::find_if來執行相同操作。
  3. 使用main函數中的while循環中的函數。

bool isNotABCD(char c) 
{ 
    return !((c == 'A') || (c == 'B') || (c == 'C') || (c == 'D')); 
} 

bool isValidInput(std::string const& str) 
{ 
    return (std::find_if(str.begin(), str.end(), isNotABCD) == str.end()); 
} 

int main() 
{ 
    string strand1; 

    cout << "Enter String 1:\n"; 
    while (cin >> strand1 && !isValidInput(strand1)) 
    { 
     cout << "Invalid Input"; 
     system("cls"); 
     cout << "Enter String 1:\n"; 
    } 
    cout << "ok"; 
} 

更新

您還可以使用的isValidInput()一個簡單的版本,由於@Blastfurnace的意見。

bool isABCD(char c) 
{ 
    return (c == 'A') || (c == 'B') || (c == 'C') || (c == 'D'); 
} 

bool isValidInput(std::string const& str) 
{ 
    return (std::all_of(str.begin(), str.end(), isABCD)); 
} 

更新2

您還可以使用的isValidInput()一個更加簡單的版本,由於@JorenHeit的意見。

bool isValidInput(std::string const& str) 
{ 
    return (std::find_first_not_of("ABCD") == std::string::npos); 
} 
+3

由於你有一個謂詞,我認爲使用['std :: all_of','std :: any_of','std :: none_of']之一可能會更簡單(http://en.cppreference.com/ w/cpp/algorithm/all_any_none_of)而不是find_if。 – Blastfurnace

+0

@Blastfurnace,絕對更好。謝謝。 –

+1

@RSahu Or ....你可以使用'return str.find_first_of(「ABCD」)== std :: string :: npos;'我認爲這更多地在OP級別上,因爲它避免了算法和迭代器。另外,它不應該是一個const ref? – JorenHeit

相關問題