指针不起作用的C ++程序

时间:2013-10-17 23:12:00

标签: c++ arrays pointers struct

我是初学者而且被卡住了。我写了这个,到目前为止它没有用。在“添加或删除交易者”之后它什么都不做。任何关于如何使这个功能的帮助或花絮将非常感激。谢谢。

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

2 个答案:

答案 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的名称。