Привет, поэтому мой вопрос: как я могу продолжить работу с новыми вводами после инструкции else? В моей программе я написал оператор else, который, если вход не является ни 1, ни 2, пользователь должен поместить новое значение, чтобы получить результат, который он хочет. Но после моего другого заявления моя программа отключается. Я не знаю, как это исправить. Я очень новичок в c++, поэтому, пожалуйста, держите суровые комментарии к себе... Вот мой код:
// This program will allow the user to input from the keyboard
// whether the last word to the following proverb should be party or country:
// "Now is the time for all good men to come to the aid of their _______"
// Inputting a 1 will use the word party. A 2 will use the word country.
#include <iostream>
#include <string>
using namespace std;
void writeProverb(int);
int main ()
{
int wordCode;
cout << "Given the phrase:" << endl;
cout << "Now is the time for all good men to come to the aid of their ___" << endl;
cout << "Input a 1 if you want the sentence to be finished with party" << endl;
cout << "Input a 2 if you want the sentence to be finished with country." << endl;
cout << "Please input your choice now" << endl;
cin >> wordCode;
cout << endl;
writeProverb(wordCode);
return 0;
}
void writeProverb (int number)
{
if (number == 1)
cout << "Now is the time for all good men to come to the aid of their party." << endl;
else if (number == 2)
cout << "Now is the time for all good men to come to the aid of their country." << endl;
else
{
cout << "I'm sorry but that is an incorrect choice: Please input a 1 or 2" << endl;
}
}
Поэтому, в основном, после инструкции else, я хочу, чтобы моя программа дождалась, когда пользователь войдет в 1 или 2, а не просто выключится.
do {
cout << "Please input your choice now" << endl;
cin >> wordCode;
cout << endl;
writeProverb(wordCode);
}while (wordCode != 1 && wordCode != 2);
Этот код выходит, если пользователь вводит 1 или 2. Остается в другом месте.
Вы хотите иметь конструкцию do-while
пока не получите юридическую ценность, как уже указывал Сакти Кумар.
Тем не менее, вы не хотите переводить знания о том, какое юридическое значение имеет основное значение. Поэтому writeProverb
метод writeProverb
если это значение является законным или нет. Это держит вещи в правильном уровне абстракции. Вы также должны рассмотреть возможность обновления печати "меню" с помощью объекта, таким образом связывая все вместе.
// ... in main()
do {
cout << "Please input your choice now" << endl;
cin >> wordCode;
cout << endl;
writeProverb(wordCode);
} while( !writeProverbIfLegalNumber(wordCode) );
}
bool writeProverbIfLegalNumber (int number) {
if (number == 1) {
cout << "Now is the time for all good men to come to the aid of their party." << endl;
return true;
}
else if (number == 2) {
cout << "Now is the time for all good men to come to the aid of their country." << endl;
return true;
}
else
{
cout << "I'm sorry but that is an incorrect choice: Please input a 1 or 2" << endl;
}
return false;
}
writeProverb
, тем не менее, +1 за это.
в этом случае вы можете поместить утверждение суждения в "главную" функцию. Вы можете использовать инструкцию "while" для управления логикой.
boolean flag = true;
while(flag){
cout<<"input";
cin>>wordCode;
if(wordCode==1 || wordCode==2){
flag=false;
writeProverb(wordCode);
}
}
Это основная логика, вы должны прочитать о циклах и о том, как их использовать. Это в while
цикл продолжается, пока не wordCode от 1 до 2 включительно; другими словами, он продолжается до тех пор, пока вы не получите 1 или 2.
int main ()
{
int wordCode;
cout << "Given the phrase:" << endl;
cout << "Now is the time for all good men to come to the aid of their ___" << endl;
cout << "Input a 1 if you want the sentence to be finished with party" << endl;
cout << "Input a 2 if you want the sentence to be finished with country." << endl;
do
{
cout << "Please input your choice now 1 or 2: " << endl;
cin >> wordCode;
} while(!(1 <= wordCode && wordCode <=2));
cout <<endl;
writeProverb(wordCode);
return 0;
}