我是初学者而且被卡住了。我写了这个,到目前为止它没有用。在“添加或删除交易者”之后它什么都不做。任何关于如何使这个功能的帮助或花絮将非常感激。谢谢。
#include<iostream>
#include<iomanip>
#include<string>
using namespace std;
struct Department{
string deptName;
int numTraders;
};
void addTraders(Department *, int );
void removeTraders(Department *, int);
int main(){
char addOrRemove;
Department departments[10] = {
{"Bank Loan", 10},
{"Conservative Allocation", 9},
{"Europe Stock", 10},
{"Domestic", 21},
{"Asia", 10},
{"Large Growth", 5},
{"Long-term Bond", 5},
{"Money Market", 25},
{"Emerging Market", 18},
{"Large Blend", 12}
};
int choice, numberToAdd, numberToRemove;
Department* p_departments = departments;
for(int i = 0; i < 10; i++){
cout << "Department # " << (i + 1) << ", Name: " << p_departments[i].deptName <<
", Traders: " << p_departments[i].numTraders << endl;
}
cout << endl;
do{
cout << "Enter 0 to quit, or choose a department number: ";
cin >> choice;
cout << "Add or remove traders (A or R) ? ";
cin >> addOrRemove;
if(addOrRemove == 'A' || 'a'){
cout << "how many traders to add" << endl;
cin >> numberToAdd;
addTraders(&departments[choice-1] ,numberToAdd);
}
else if(addOrRemove == 'R' || 'r'){
cout << "how many traders to remove" << endl;
cin >> numberToRemove;
removeTraders(&departments[choice-1],numberToRemove);
}
else{
cout << addOrRemove << " is not a valid selection. \n";
}
for(int i = 0; i < 10; i++){
cout << "Department # " << (i + 1) << ", Name: " << p_departments[i].deptName <<
", Traders: " << p_departments[i].numTraders << endl;
}
cout << endl;
}while(count != 0);
system("pause");
return 0;
}
void addTraders(Department *dept, int numAdd){
dept->numTraders += numAdd;
}
void removeTraders(Department *dept, int numRemove){
dept->numTraders += numRemove;
}
答案 0 :(得分:0)
以下条件始终评估为true
;即使它是false || 'a'
,'a'
〜&gt; true
:
if(addOrRemove == 'A' || 'a'){ ...
原意是:
if(addOrRemove == 'A' || addOrRemove == 'a'){ ...
但是,当addOrRemove
被声明为char
时,则:
cin >> addOrRemove;
可能只是读取一个换行符或一些空格。将addOrRemove
声明为std::string
并将您的条件更改为:
if(addOrRemove == "A" || addOrRemove == "a"){ ...
在您阅读choice
并且0
之后,您应该break
您的循环,以便它不会尝试访问索引0 - 1
处的元素:
cin >> choice;
if (choice == 0) break; // <-- THIS
答案 1 :(得分:0)
首先取代
if(addOrRemove == 'A' || 'a'){
你应该写
if(addOrRemove == 'A' || addOrRemove == 'a'){
其次你应该定义变量计数,因为似乎编译器认为count是标准算法std :: count的名称。