gpt4 book ai didi

c++ - struct 中的 Char 数组切掉第一个字母

转载 作者:太空宇宙 更新时间:2023-11-04 14:12:49 25 4
gpt4 key购买 nike

我刚刚开始学习 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() 移到循环之前。

关于c++ - struct 中的 Char 数组切掉第一个字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13349172/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com