【发布时间】:2018-04-03 00:30:30
【问题描述】:
我的函数中的 for 循环没有完成它的完整运行。在询问学生的地址后,它只输出:
"Enter City: Enter Age: Enter Name: Enter Street Address: Enter City: Enter
Age: Enter Name: Enter Street Address: Enter City: Enter Age:"
而不是让用户输入他们的其余信息。基本上 for 循环应该为每个学生循环。因此,如果有 3 个学生,它应该循环 3 次,以便每个学生都可以输入他们的信息。 这是我到目前为止的代码:
#include <iostream>
#include <string>
#include <iomanip>
#include <cstring>
using namespace std;
struct Address
{
char sStreet[255];
char sCity[255];
};
struct Student
{
char sName[255];
Address address;
int nAge;
};
void initializeData(Student * pStudents, int size);
// void sortData(Student * pStudents, int size);
// void displayData(Student * pStudents, int size);
int main()
{
int size = 0;
cout << "Enter the number of students in your classroom: ";
cin >> size;
Student * pStudents = new Student[size];
initializeData(pStudents, size);
delete [] pStudents;
pStudents = NULL;
return 0;
}
void initializeData(Student * pStudents, int size)
{
for(int i = 0; i < size; i++)
{
cout << "Enter Name: ";
cin >> pStudents[i].sName;
cout << "Enter Street Address: ";
cin >> pStudents[i].address.sStreet;
cout << "Enter City: ";
cin >> pStudents[i].address.sCity;
cout << "Enter Age: ";
cin >> pStudents[i].nAge;
}
}
我真的很困惑为什么它没有完成它的循环:(这个任务还有更多,但我被困在这里。我不确定为什么 for 循环没有完全完成,我试图得到在上课时间提供帮助,但没有人可以帮助我解决这个问题。
更新:感谢最先发表评论的两位用户!您的两个建议都对我有帮助,在修复我的代码后,这就是现在的工作:
#include <iostream>
#include <string>
#include <iomanip>
#include <cstring>
using namespace std;
struct Address
{
char sStreet[255];
char sCity[255];
};
struct Student
{
char sName[255];
Address address;
int nAge;
};
void initializeData(Student * pStudents, int size);
// void sortData(Student * pStudents, int size);
// void displayData(Student * pStudents, int size);
int main()
{
int size = 0;
cout << "Enter the number of students in your classroom: ";
cin >> size;
cin.ignore();
Student * pStudents = new Student[size];
initializeData(pStudents, size);
delete [] pStudents;
pStudents = NULL;
return 0;
}
void initializeData(Student * pStudents, int size)
{
for(int i = 0; i < size; i++)
{
cout << "Enter Name: ";
cin.getline(pStudents[i].sName, 255);
cout << "Enter Street Address: ";
cin.getline(pStudents[i].address.sStreet, 255);
cout << "Enter City: ";
cin.getline(pStudents[i].address.sCity, 255);
cout << "Enter Age: ";
cin >> pStudents[i].nAge;
cin.ignore();
}
}
【问题讨论】:
-
您有问题吗?
标签: c++ function for-loop struct dynamic-arrays