• 5

C++問題

#include<iostream>
#include<cstdlib>
using namespace std;
union mydata
{
char name[15];
char number[7];;
}teacher;
int main(void)
{
char k;
cout<<"請輸入姓名:";
cin.getline(teacher.name,15);
cout<<"請輸入代號:";
cin.getline(teacher.number,7);
do{
cout<<"請問您的性別 (1)男性 (2)女性: ";
cin>>k;
}while((k>50)||(k<49));
switch(k)
{
case '1':
char m;
cout<<"是否役畢? (1)YES (2)NO ";
cin>>m;
if(m==49){
cout<<"姓名:"<<teacher.name<<endl;
cout<<"代號"<<teacher.number<<endl;
cout<<"男性"<<endl;
cout<<"役畢"<<endl;
}
if(m==50){
cout<<"姓名:"<<teacher.name<<endl;
cout<<"代號"<<teacher.number<<endl;
cout<<"男性"<<endl;
cout<<"未役"<<endl;
}
break;
case '2':
int h;
cout<<"打字速度?";
cin>>h;
cout<<"姓名:"<<teacher.name<<endl;
cout<<"代號"<<teacher.number<<endl;
cout<<"女性"<<endl;
cout<<"打字速度"<<h<<"字"<<endl;
break;
}




system("pause");
return 0;
}

============================================================

真奇怪!!一直在姓名的地方出錯!!
有誰能幫我除錯一下
小弟不才這麼簡單的東西都不會
2007-10-14 17:08 發佈
文章關鍵字 C++ 問題
你確定你的結構是要用 union ? 改成 struct 看看.
JHLX wrote:
你確定你的結構是要用...(恕刪)


拍謝!!老師指定要用union!!
roosalsa wrote:
拍謝!!老師指定要用...(恕刪)


理由呢? 還有你的結構要求是什麼樣子,如果一點說明都沒有實在是沒有道理.
roosalsa wrote:
拍謝!!老師指定要用union!!


是了,老師要敎你們 union 和 struct 不同的地方, 把書上這個地方讀一讀,跟大家說說這兩個有何不同 或者把你的 union 改成 struct, 看看為何結果不一樣
union好像是共用一塊記憶體...所以造成此問題...
你們老師限定union...應該就是希望你去瞭解此特性吧...


查一下HELP吧
Description

Use unions to define variables that share storage space.

The compiler allocates enough storage in a_number to accommodate the largest element in the union.

Unlike a struct, the members of a union occupy the same location in memory. Writing into one overwrites all others.

Use the record selector (.) to access elements of a union .
liming wrote:
union好像是共用...(恕刪)


那怎樣可以用"union"寫出正確的答案?
我只有這樣的問題
其實也不是老師指定
應該是我自學書上指定
cin.getline(teacher.number,15);

--> cin.getline(teacher.number,7);

這不是 union 的答案.. 這是怕輸入爆掉
JHLX wrote:
cin.getline(teacher.number,15);

--> cin.getline(teacher.number,7);


這個答案是錯的
roosalsa wrote:
那怎樣可以用"uni...(恕刪)


這問題...已經不是問題了...請你再多看看union的定義...
你再多看看那本書吧...如果還看不懂..換本書吧~

另外你變數型態定義怪怪的...你好像特別喜歡用char...
union裡面兩個char...我好像沒看過這樣用...
  • 5
內文搜尋
X
評分
評分
複製連結
Mobile01提醒您
您目前瀏覽的是行動版網頁
是否切換到電腦版網頁呢?