0

I am a beginner and am stuck. I have written this and so far it is not working. After "Add or Remove Trader" it does nothing. Any help or tidbits on how to make this functional would be greatly appreciated. Thank you.

#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;
} 
4

2 回答 2

0

The following condition is always evaluated as true; even if it's false || 'a', 'a' ~> true:

if(addOrRemove == 'A' || 'a'){ ...

it was meant to be:

if(addOrRemove == 'A' || addOrRemove == 'a'){ ...

However when addOrRemove is declared as a char, then:

cin >> addOrRemove;

might just read a new-line character or some white space. It would be probably more reasonable to declare addOrRemove as std::string and change your condition to:

if(addOrRemove == "A" || addOrRemove == "a"){ ...

And after you read choice and it's 0, you should break your loop so that it won't try to access element at index 0 - 1:

cin >> choice;
if (choice == 0) break;   // <-- THIS
于 2013-10-17T23:16:26.990 回答
0

First of all instead of

if(addOrRemove == 'A' || 'a'){

you should write

if(addOrRemove == 'A' || addOrRemove == 'a'){

And secondly you should define variable count because it seems that the compiler thinks that count - is name of standard algorithm std::count.

于 2013-10-17T23:23:10.547 回答