我刚刚开始学习 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;
}
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;
调用留在流中的换行符。另一方面,istream::getline()
会丢弃尾随的 '\n'
,因此每个后续迭代都会等待并丢弃输入的第一个字符。
将 cin.ignore()
移到循环之前。
我是一名优秀的程序员,十分优秀!