#include <iostream>
#include <string>
using namespace std; // For speed
int main()
{
bool saidYes = false;
string input;
while (!saidYes)
{
cout << "Input yes or no: ";
getline(cin, input);
if (input == "no" || input == "n" || input == "NO")
{
saidYes = true; // breaks the loop
}
if (input == "y" || input == "Y" || input == "yes" || input == "YES")
{
saidYes = false;
}
}
return 0;
}
あなたが不要なコードの巨大な部分を排除するために、上記の例を使用することができ、私は他の文を追加しないことを選択したが、それは意志あなたがここにそれを追加しても動作します。
また、このコードをさらに圧縮することもできますが、これは、これをよりうまく利用するための簡単な例です。
上記のように、==を使用して文字列を比較することができます。他の特定の言語から来ている場合は、慣れ親しんで笑うことができます。
私は文字列とアルゴリズムを含んでいます。何らかの理由で、入力時にy/yesやn/noが得られないように常に動作します。
アルゴリズムは、あなたがしようとしていることに必要ではなく、文字列入力の読み取りと受け入れを必要以上に困難にします。
上記を参照すると、string input;
が表示されます。これは、ユーザー入力文字列を格納するために使用できる変数です。
また、getline(cin, input);
が表示されます。これは、ユーザーが入力を求められたときに入力する文字列を「読む」ために使用できます。
@Kelvin Shadewing私の最初の答えはあなたの質問でのみ指示されました。この次の例は、私の下のあなたのコメントに向けられています!
あなたはかなりのオプションを持っていますが、ユーザがはいまたはいいえを入力し、入力に応じて特定の結果を生成したいと思っていることを前提に、はいまたはいいえのいずれかを入力すると、元の回答を変更する必要があります。
#include <iostream>
#include <string>
using namespace std; // For speed
int main()
{
bool saidYes = false;
string input;
while (!saidYes)
{
cout << "Input yes or no: ";
getline(cin, input);
if (input == "no" || input == "n" || input == "NO")
{
saidYes = true;
cout << "you said no" << endl;
/* breaks the loop by changing the
bool (true or false flag) to true, if you want to produce a specific result,
whether it's a simple output statement or a function call you can put it here
*/
}
else if (input == "y" || input == "Y" || input == "yes" || input == "YES")
{
saidYes = true;
cout << "You said yes" << endl;
/* breaks the loop by changing the
bool (true or false flag) to true, if you want to produce a specific result,
whether it's a simple output statement or a function call you can put it here
*/
}
else saidYes = false;
}
return 0;
}
'toupper'は0..255の範囲の値を期待しているので' transform(input.begin()、input.end()、input.begin()、toupper) 'はポータブルではありません。 'はしばしば' signed'型なので、未定義の振る舞いを簡単に引き起こすことができます。 – Simple
私はそれを念頭に置いておきます。ありがとうございました。 –
@ Xiremaをコード化する方法を学ぶために、そしてそれが悪い習慣である理由を理解し、他の名前空間を使うことを開始するまで、それはそうではありません。人々はすべてのことをすべて知っているわけではないことを忘れる傾向があります。 – Afflicted