我有这种格式的文本:
NAME(char) ID(int) MARK(int)
例如:
JOSH 1234 100
SARA 5678 90
..
..
我想读取该文件,进入PARAMS的学生结构,然后打印在屏幕上(你可以在代码中看到)。
我的问题是,它似乎我不能正确读取的名字,这条线:while (file >> id >> word >> grade)
- 是获得id
和mark
正确的,但在变量word
名称(这是char *
)越来越十六进制地址一样0x000a8520。
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
struct Student
{
int id;
char * name = new char [25];
int mark;
};
int makeStudentsArr(Student * ptr, char * address);
void printArr(Student * ptr, int number);
int main() {
char * address = new char[26];
Student * myptr = new Student[50];
cin >> address;
int count;
count = makeStudentsArr(myptr, address);
printArr(myptr, count);
system("pause");
return 0;
}
int makeStudentsArr(Student * ptr, char * address) {
ifstream file;
file.open(address);
char * word = new char[25];
int id,grade;
int index = 0;
while (file >> id >> word >> grade) {
ptr[index].id = id;
ptr[index].name = word;
ptr[index].mark = grade;
index++;
}
return index;
}
void printArr(Student * ptr, int number) {
for (int i = 0;i < number;i++) {
cout << "name: " << (ptr + i)->name << " id: " << (ptr + i)->id << " mark: " << (ptr + i)->mark << endl;
}
}
更改此:
ptr[index].name = word;
为此:
strcpy(ptr[index].name, word);
因为第一个副本的指针,而第二个副本的实际字符串(其中指针指向)!
但是,你的程序不delete
你new
,这会导致内存泄漏动态分配的内存。
如果您使用的std::string
代替C字符串这会容易得多。此外,它也将是比较容易,如果你使用的std::vector
,而不是普通的C数组。