所以对于我的项目,我必须......
使用以下格式创建结构:struct PERSON {string name;年龄; float gpa;};
要求用户输入他们想要输入的记录数 .
创建PERSON类型的动态数组p,以便能够保存第2部分中的所有记录
在第2部分中将数据读入数组p
显示数组p
但是,每当我运行程序并开始输入数据时,它就不会让我输入多组数据,输出似乎没什么意义 .
这是我的代码:
#include "stdafx.h"
#include
#include
#include
#include
using namespace std;
struct PERSON
{
string name;
int age;
float gpa;
};
PERSON *p;
int main()
{
int count;
cout << "Please enter the number of records you wish to enter: ";
cin >> count;
p = new (nothrow) PERSON[count];
if (p == nullptr)
cout << "Error: memory could not be allocated";
for (int i = 0; i < count; i++)
{
cout << "Enter name, age, and gpa: ";
getline(cin, p[i].name);
cin >> p[i].age;
cin >> p[i].gpa;
cout << endl;
}cout << endl;
cout << "This is the content of array p: " << endl;
cout << right << setw(8) << "NAME" << setw(7) << "AGE" << setw(7) << "GPA" << endl;
cout << "--------------------------" << endl;
for (int i = 0; i < count; i++)
{
cout << p[i].name << " " << p[i].age << " " << p[i].gpa << endl;
}
return 0;
}
现在,当我将数据从文件复制到动态数组结构中时,这种格式似乎工作得很好,但是我现在似乎无法使用它来处理用户输入 .
以下是该程序的试运行:
Please enter the number of records you wish to enter: 3
Enter name, age, and gpa: Robert 21 2.1 // This is the info I tested
Enter name, age, and gpa:
Enter name, age, and gpa:
This is the content of array p:
NAME AGE GPA
--------------------------
-842150451 -4.31602e+008 //?
-842150451 -4.31602e+008 //?
-842150451 -4.31602e+008 //?
Press any key to continue . . .
我现在可能已经超过了代码二十多次,并且已经找了一段时间的答案了 . 任何建议/分析/评论将不胜感激 .
So @AndyG suggested that I change the getline(cin, p[i].name) to cin >> p[i].name and that seemed to clear things up. Thank you!
Sorry to trouble everyone over such a silly muck-up.