简单的C ++控制台I / O问题

时间:2013-06-28 19:10:13

标签: c++ input output

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

这个程序显示了很多垃圾,如下:

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:

有人可以向我解释原因并告诉我如何纠正这个程序吗?我也尝试用cin&gt;&gt;替换(cin&gt;&gt; ch).get() CH。它也行不通。非常感谢!

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分: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。