简体   繁体   中英

Read words and numbers from text file (c++)

I have a text with this format:

NAME(char) ID(int) MARK(int)

for example:

JOSH 1234 100
SARA 5678 90
..
..

I want to read this file, enter the params to a students struct and then print it on the screen ( you can see in the code).

My problem is that it seems I can't read the name properly, and this line: while (file >> id >> word >> grade) - is getting the id and the mark correct, but the name in the variable word (which is char * ) is getting hex addresses like 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;
    }
}

Change this:

ptr[index].name = word;

to this:

strcpy(ptr[index].name, word);

since the first copies the pointer , while the second copies the actual string (where the pointer is pointing to)!


However, your program does not delete the memory you dynamically allocated with new , which results in memory leaks.

It would be much easier if you used an std::string instead of C strings. Moreover, it would also be easier, if you used an std::vector instead of plain C arrays.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM