0
#include <iostream>
using namespace std;

const int Max=20;

struct bop
{
    char fullname[Max];
    char title[Max];
    char bopname[Max];
    int preference;
};

int main()
{
    bop a[5]=
    {
        {"Steve Jobs", "BFF", "Rita",0},
        {"Bill Gates", "BFF2", "Ann",1},
        {"Mark", "BFF3", "Boss", 2},
        {"Edward", "BFF4", "Jiezha", 2},
        {"Larry Page", "BFF5", "Michele", 1}
    };
    cout << "Benevolent Order of Programmers Report\n";
    cout << "a. display by name         b. display by title\n"
            "c. display by bopname      d. display by preference\n"
            "q. quit\n"
            "Enter your choice: ";
    char ch;
    (cin >> ch).get();
    int i;
    while (ch!='q')
    {
        switch (ch)
        {
            case 'a': for (i=0; i<Max; i++) cout << a[i].fullname << endl; break;
            case 'b': for (i=0; i<Max; i++) cout << a[i].title << endl; break;
            case 'c': for (i=0; i<Max; i++) cout << a[i].bopname << endl; break;
            case 'd': for (i=0; i<Max; i++)
                        switch (a[i].preference)
                        {
                            case 0: cout << a[i].fullname << endl; break;
                            case 1: cout << a[i].title << endl; break;
                            case 2: cout << a[i].bopname << endl; break;
                        }
                      break;
        }
        cout << "Next choice: ";
        (cin >> ch).get();
    }
    cout << "Bye!" << endl;
    return 0;
}

This program displays a lot of rubbish as follows:

Benevolent Order of Programmers Report
a. display by name          b. display by title
c. display by bopname       d. display by preference
q. quit
Enter your choice: a
Steve Jobs
Bill Gates
Mark
Edward
Larry Page
^?&i?
'=YV?
K>YV?
f?YV?
??YV?
xterm-256color
11dry7st9vkb200000gn/T/
T3PDw/Render
anguage (C++)
B6
qUSg/Listeners
Message=/tmp/launch-Gpgr3C/Apple_Ubiquity_Message
/bin:/usr/sbin:/sbin:/usr/local/bin
ge (C++)/cpp
boris
Next choice:

Can anybody explain to me the reason and tell me how to correct this program? I've also tried to replace (cin >> ch).get() with just cin >> ch. It also doesn't work. Thanks a lot!

4

2 回答 2

1

看起来您正在迭代超出数组的范围。为什么要迭代到 20(MAX)?看起来你应该迭代到 5,而不是。

此外,您应该在问题中包含您的预期输出。

于 2013-06-28T19:14:01.820 回答
1

问题出在您的内部实现中。您执行以下操作:

case 'a': for (i=0; i<Max; i++) cout << a[i].fullname << endl; break;
//case 'b': ...

如果你看顶部,Max 定义为 20:

const int Max=20;

但是您的数组中只有 5 个成员:

bop a[5]=
{
    {"Steve Jobs", "BFF", "Rita",0},
    {"Bill Gates", "BFF2", "Ann",1},
    {"Mark", "BFF3", "Boss", 2},
    {"Edward", "BFF4", "Jiezha", 2},
    {"Larry Page", "BFF5", "Michele", 1}
};

因此,当它打印索引 6-19 的值时,它会打印垃圾。计算垃圾的行数加上正确输出的行数。完美 20。

于 2013-06-28T19:16:52.117 回答