gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 03:14:29 24 4
gpt4 key购买 nike

#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 >> ch 替换 (cin >> ch).get()。它也不起作用。非常感谢!

最佳答案

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

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。

关于c++ - 简单的 C++ 控制台 I/O 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17371970/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com