如何将数据从文本文件分配到结构C ++

问题描述

我想将文件内容分配到结构中,但我不断收到此错误,如果有人知道如何将数据逐行分配到结构数组中,请也告诉我。

error: invalid operands to binary expression ('basic_ostream<char,std::__1::char_traits<char> >' and 'const char [2]')

我不知道这是什么问题。这是代码

#include <cstdlib>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <istream>
#include <ostream>
using namespace std;

struct StudentInfo {
    char fname[30];
    char lname[30];
    int id;
    char address[30];
    char PhoneNumber[20];
};

void read_file() {
    ifstream data("text.txt");
    StudentInfo array[11];
    if(!data.fail) {
        int i;
        for(int i = 0; i <= 11; i++) {
            data >> array[i].fname;
            data >> array[i].lname;
            data >> array[i].id;
            data >> array[i].address;
            data >> array[i].PhoneNumber;
        }
        for(int i = 0; i <= 11; i++) {
            cout << array[i].fname >> " " << array[i].lname << " " << array[i].id >>
                " " << array[i].address >> " " << array[i].PhoneNumber;
        }
    }
}

void print_student(StudentInfo s) {
    cout << s.fname >> " " << s.lname >> " " << s.id >> " " << s.address >>
        " " << s.PhoneNumber;
}

void search(StudentInfo array[]) {
    int sid;
    //    string last;
    cout << "Enter id";
    cin >> sid;
    for(int i = 0; i < 1000; i++) {
        if(array[i].id == sid) {
            print_student(array[i]);
        }
    }
}

int main() {
    StudentInfo array[11];
    read_file();
    search(array);

    return 0;
}

解决方法

此声明

cout<<array[i].fname>>" "<<array[i].lname<<" "<<array[i].id>>" "<<array[i].address>>" "<<
            array[i].PhoneNumber;

没有道理。实际上,由于在本部分中同时使用了运算符>

cout<<array[i].fname>>" "

您所拥有的声明

std::cout >> " "

但未为输出流std :: cout定义运算符>>。

看来你的意思

cout<<array[i].fname << " "
                     ^^^

在语句中您错误地使用运算符>>的任何地方。

如果您有一个包含11个元素的数组,请注意

StudentInfo array[11];

则索引的有效范围是[0,11 )。那就是使用索引11,您正在访问数组之外​​的内存。

for(int i = 0; i <= 11; i++) {
            data >> array[i].fname;
            //...
,

首先,您的迭代将在索引范围之外

for (int i=0; i<=11;i++) // it would try to access invalid index
for (int i=0; i<11;i++)  // you should try this instead

第二,您必须按以下步骤更正该行:

if(!data.fail) // It won't work
if(!data.fail()) // You have to use this

第三,您还必须如下更改此行

cout<<array[i].fname>>" "<<array[i].lname<<" "<<array[i].id>><<array[i].address>>" "<<
        array[i].PhoneNumber;   // This line should be removed
cout<<array[i].fname<<" "<<array[i].lname<<" "<<array[i].id<<" " <<array[i].address<<" "<<
        array[i].PhoneNumber; // This line should be added