2015-05-01 2 views
-1

так что в основном этот код ниже - это всего лишь три магазина, из которых пользователь покупает оружие. пользователь должен нажать кнопку выхода, чтобы выйти из одного магазина и перейти к другому.Как ограничить количество входов для следующего кода? C++

Я хочу ограничить пользователя тем, что он может купить всего 10 пушек из всех трех разделов.

Например, если пользователь покупает 10 пушек из первого магазина, покупая из других магазинов, процесс должен быть пропущен. И предположим, что если пользователь покупает 6 пушек из первого магазина и 4 из другого, то третий магазин должен быть пропущен.

Любые идеи, как реализовать это?

cout<<endl<<"enter the guns you want from store 1 and press exit to buy from other sstore"<<endl; 
cin>>a; 

while(a!="exit") 
{ 
    tmp = false; 
    for(map<string,int> :: const_iterator it = storeone.begin(); it != storeone.end(); ++it) 
    { 
     if(it->first == a) 
     { 
      b=it->second; 
      setfinalguns(a,b); 
      cout<<"you bought "<<a<<" for price "<<b<<endl; 
      spentmoney(b); 
      tmp = true; 
      break; 
     } 
    } 
    if(!tmp) 
     cout<<"This gun is not available"<<endl; 
    cin>>a; 

} 

cout<<"enter the items you want to from store two and press exit to buy from other store"<<endl; 
cin>>c; 
while(c!="exit") 
{ 
    tmp = false; 
    for(map<string,int> :: const_iterator it = stroretwo.begin(); it != storetwo.end(); ++it) 
    { 
     if(it->first == c) 
     { 
      d=it->second; 
      setfinalguns(c,d); 
      cout<<"you bought "<<c<<" for price "<<d<<endl; 
      spentmoney(d); 
      tmp = true; 
      break; 
     } 
    } 
    if(!tmp) 
     cout<<"Thisgun is not available"<<endl; 
    cin>>c; 

} 

cout<<"enter the guns you want from store three and press exit to buy from other store"<<endl; 
cin>>e; 
while(e!="exit") 
{ 
    tmp = false; 
    for(map<string,int> :: const_iterator it = storethree.begin(); it != storethree.end(); ++it) 
    { 
     if(it->first == e) 
     { 
      f=it->second; 
      setfinalguns(e,f); 
      cout<<"you bought "<<e<<" for price "<<f<<endl; 
      spentmoney(f); 
      tmp = true; 
      break; 
     } 
    } 
    if (!tmp) 
     cout<<"This gun is not available"<<endl; 
    cin>>e; 
    break; 
} 
+2

Как насчет чего-то типа 'if (number_of_guns == 10) break;' –

ответ

0

Ниже приведен модифицированный код, который решает проблему. Вам просто нужно добавить переменную счетчика (глобальную), которая будет отслеживать количество купленных оружия и увеличивать ее каждый раз, когда пользователь покупает пистолет.

Теперь, на каждой итерации циклов while, проверьте значение счетчика и перерыв, если нет. пушки Куплен 10.

int counter=0; //This will keep track of number of guns bought 
cout<<endl<<"enter the guns you want from store 1 and press exit to buy from other sstore"<<endl; 
cin>>a; 

while(a!="exit") 
{ 
    if(counter == 10) // check if user has already bought 10 guns 
    break; 
    tmp = false; 
    for(map<string,int> :: const_iterator it = storeone.begin(); it != storeone.end(); ++it) 
    { 
    if(it->first == a) 
    { 
     b=it->second; 
     setfinalguns(a,b); 
     cout<<"you bought "<<a<<" for price "<<b<<endl; 
     spentmoney(b); 
     counter++; 
     tmp = true; 
     break; 
    } 
    } 
    if(!tmp) 
    cout<<"This gun is not available"<<endl; 
    cin>>a; 

} 

cout<<"enter the items you want to from store two and press exit to buy from other store"<<endl; 
cin>>c; 
while(c!="exit") 
{ 
    if(counter == 10) 
    break; 
    tmp = false; 
    for(map<string,int> :: const_iterator it = stroretwo.begin(); it != storetwo.end(); ++it) 
    { 
    if(it->first == c) 
    { 
     d=it->second; 
     setfinalguns(c,d); 
     cout<<"you bought "<<c<<" for price "<<d<<endl; 
     spentmoney(d); 
     counter++; 
     tmp = true; 
     break; 
    } 
    } 
    if(!tmp) 
    cout<<"Thisgun is not available"<<endl; 
    cin>>c; 

} 

cout<<"enter the guns you want from store three and press exit to buy from other store"<<endl; 
cin>>e; 
while(e!="exit") 
{ 
    if(counter == 10) 
    break; 
    tmp = false; 
    for(map<string,int> :: const_iterator it = storethree.begin(); it != storethree.end(); ++it) 
    { 
    if(it->first == e) 
    { 
     f=it->second; 
     setfinalguns(e,f); 
     cout<<"you bought "<<e<<" for price "<<f<<endl; 
     spentmoney(f); 
     counter++; 
     tmp = true; 
     break; 
    } 
    } 
    if (!tmp) 
    cout<<"This gun is not available"<<endl; 
    cin>>e; 
    break; 
} 
0

В качестве объяснения к моему предыдущему комментарию, вы можете сохранить переменный для хранения количества пушек купило.

Затем добавьте простой, если заявление, как

if(number_of_guns == 10) 
    break; 

в начале вашего времени циклов. Так проще говоря, выйти из вашего цикла в то время как, если количество пушек купил 10.

Кроме того, чтобы ограничить количество орудий до 10, вы можете попробовать что-то похожее на

if(number_of_guns > 10) 
     Try_again ; // or continue 

Этом это информация о том, как это сделать, вы можете попробовать ее реализовать.