[英]Char array in struct cuts out first letter
我剛剛開始學習c ++,在整個指針/數組一章中,我正在嘗試編寫一些代碼來掌握這些概念。 我要我的代碼執行的操作是:1)詢問學生人數,2)為每個學生詢問姓名,3)在結構中為此學生分配ID和姓名,4)打印學生ID和姓名進行驗證。
問題如下。 例如,假設我選擇輸入3個學生並輸入以下名稱:
JOHN
GEORGE
NICK
程序作為學生ID /姓名打印的內容將是:
0 JOHN
1 EORGE
2 ICK
除了第一個字母,它似乎剪掉了所有名字的第一個字母。
#include <iostream>
using namespace std;
struct STUDENT
{
char chName[256];
int nID;
};
int main(){
//array tests
int i=0;
int nLoops=0; //number entered by user
STUDENT *pnStudents; //pointer to our student array
cout << "Enter number of students: ";
cin >> nLoops;
pnStudents = new STUDENT[nLoops];
for (i=0 ; i < nLoops ; i++)
{
cout << endl << "Full Name of Student " << i <<": ";
cin.ignore();
cin.getline(pnStudents[i].chName,255);
pnStudents[i].nID=i;
}
for (i=0 ; i < nLoops ; i++)
{
cout << pnStudents[i].nID << " " << *pnStudents[i].chName << endl;
}
system("pause");
return 0;
}
cin.ignore();
不帶參數的cin
丟棄大小為1的流。
istream&ignore(streamsize n = 1,int delim = EOF);
提取和丟棄字符從輸入序列中提取字符並丟棄它們。
刪除它。 那似乎是代碼中唯一的事情,它可以吃掉一個字符。 另外,如果您需要使用ignore,請使用以下命令:
cin.ignore(256,' ');
^ ^ (number of char, delim)
如果試圖忽略用作nLoops
輸入的nLoops
,則不必在每次迭代中都這樣做。
for (i=0 ; i < nLoops ; i++)
{
cout << endl << "Full Name of Student " << i <<": ";
cin.ignore();
cin.getline(pnStudents[i].chName,255);
pnStudents[i].nID=i;
}
在循環的第一次迭代中, ignore()
提取cin >> nLoops;
留在流中的cin >> nLoops;
呼叫。 另一方面, istream::getline()
丟棄結尾的'\\n'
,因此每個后續迭代都將等待並丟棄輸入的第一個字符。
將cin.ignore()
循環之前。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.