我試圖讓C++程序管理學生列表,但從一開始就陷入錯誤。這是我的計劃:存儲字符數組值錯誤(C++)
#include<iostream>
#include<string.h>
using namespace std;
struct Candidate
{
char id[5];
char fullname[30];
int reading, listening,total;
};
int main()
{
struct Candidate can[100];
int n=0;
do {
cout << "Input number of candidate:";
cin >> n;
if (n <= 0 || n>=50)
cout << "Candidate number must be between 0 and 50:\n";
} while (n <= 0 || n>=50);
for (int i = 0; i < n; i++)
{
cout << "Input information for candidate number " << i + 1 << endl;
cin.ignore(32323, '\n');
cout << "Input ID(only 5 character):";
gets(can[i].id);
cout << "Input full name:";
gets(can[i].fullname);
do {
cout << "Input reading mark:";
cin >> can[i].reading;
if(can[i].reading < 5 || can[i].reading>495)
cout<<"Your reading mark is not between 5 and 495\n";
} while (can[i].reading < 5 || can[i].reading>495);
do {
cout << "Input listening mark:";
cin >> can[i].listening;
if(can[i].listening < 5 || can[i].listening>495)
cout<<"Your listening mark is not between 5 and 495\n";
} while (can[i].listening < 5 || can[i].listening>495);
can[i].total = can[i].reading + can[i].listening;
}
cout << endl << can[0].id<<endl;
}
,所以我得到這樣的輸出:
Input number of candidate:1
Input information for candidate number 1
Input ID(only 5 character):EW2RR
Input full name:Test1
Input reading mark:344
Input listening mark:233
EW2RRTest1
好像全名的值寫入不斷地ID。我嘗試了很多方法來修復,但無法弄清楚。有人有線索嗎?
也許它會更容易使用'std :: string'和相關的流函數。畢竟這是C++。如果你能夠傳遞緩衝區的長度,那麼'fgets'是一個更好的選擇。 –
查看''輸入ID(只有5個字符)「,你應該使用'char id [6]'而不是'char id [5]'。可能還有其他一些問題,你應該學習如何調試你的代碼(問題的底線意味着你正在嘗試修復它而不進行調試)。 –