#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;
}
此程序會顯示大量垃圾如下:簡單的C++控制檯I/O問題
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()。它也不起作用。非常感謝!
如果你正在編寫C++,然後使用std :: string和std :: vector。一旦你瞭解了STL,你就會體會到它提供的優勢。但是,這並不意味着你只需跳過數組。一旦你真正理解了數組和指針,移動到STL。 –
@ScepticalJule非常感謝您的建議! – user1050165