C++ 读取一个包含10个数据项的文件,这些数据项填充数组create in struct,并在填充后显示数组的内容

C++ 读取一个包含10个数据项的文件,这些数据项填充数组create in struct,并在填充后显示数组的内容,c++,C++,原始问题附呈。我无法将文件填充到数组中,然后显示它。该文件只有10个数字。这是c语言++ #include <fstream> #include <iostream> #include <cstdlib> using namespace std; int main(int argc, const char * argv[]) { const int SIZE = 10; struct stemp{ int stud_id_num; int

原始问题附呈。我无法将文件填充到数组中,然后显示它。该文件只有10个数字。这是c语言++

#include <fstream>
#include <iostream>
#include <cstdlib>


using namespace std;


int main(int argc, const char * argv[]) {
const int SIZE = 10;

struct stemp{
   int stud_id_num;
   int num_credit_completed;
   double cum_gpa;

 }stemp[SIZE];



ifstream inputFile;
inputFile.open("stemp.txt");

int count = 0;
 while(!inputFile.eof()){
     inputFile >> stemp[SIZE];
 }


 inputFile.close();


return 0;

}
#包括
#包括
#包括
使用名称空间std;
int main(int argc,const char*argv[]{
常数int SIZE=10;
结构stemp{
int stud_id_num;
完成的积分数;
双倍平均绩点;
}stemp[尺寸];
ifstream输入文件;
open(“stemp.txt”);
整数计数=0;
而(!inputFile.eof()){
输入文件>>stemp[大小];
}
inputFile.close();
返回0;
}
这里有几个错误

首先
while(!inputFile.eof()){
在文件结束之前不是正确的读取方法。它应该是
while(inputFile>>…){

第二个
inputFile>>stemp[SIZE];
读入
stemp[10]
但您的数组只有10码,所以
stemp[10]
不存在。您可能的意思是

inputFile >> stemp[count];
count++;
这样,根据
count
变量的值,每次读取都会进入数组的不同元素

把这些放在一起你就有了

int count = 0;
while (inputFile >> stemp[count]) {
    count++;
}
这个循环现在是正确的,但恐怕你最大的错误还没有出现。你可以看到
inputFile>>stemp[count]不起作用。C++没有神奇地知道如何将文件读入到你的结构中。你必须编写代码来完成这一点。你必须编写一个与你的文件和结构一起工作的版本<>代码> <代码>。< /P>
换句话说,你必须写这个

istream& operator>>(istream& in, stemp& s)
{
    // code to read s from in goes here
}

这个解决方案怎么样:

stemp.txt

main.cpp

#包括
#包括
使用名称空间std;
constexpr size\u t size=10;
结构stemp
{
int-id;
国际学分;
双倍平均绩点;
};
void printStemp(stemp const&s、int const&index)
{
printf(
“Stemp%d\nid:%d\n编辑:%d\n通用gpa:%.2f\n\n”,
索引,s.id,s.credits,s.CumU gpa
);
}
int main()
{
stemp arr[尺寸];
ifstream输入文件;
open(“stemp.txt”);
if(inputFile.fail())
返回0;
对于(大小i=0;i>arr[i].id>>arr[i].credits>>arr[i].cum_gpa;
inputFile.close();
库特
1 2 2.1
3 4 3.2
5 6 5.3
7 8 7.4
9 10 11.5
11 12 13.6
13 14 17.7
15 16 19.8
17 18 23.9
19 20 27.10
#include <fstream>
#include <iostream>

using namespace std;

constexpr size_t SIZE = 10;

struct stemp
{
    int id;
    int credits;
    double cum_gpa;
};

void printStemp(stemp const& s, int const& index)
{
    printf(
        "Stemp %d\nid: %d\ncredits: %d\ncum_gpa: %.2f\n\n",
        index, s.id, s.credits, s.cum_gpa
    );
}

int main()
{
    stemp arr[SIZE];

    ifstream inputFile;
    inputFile.open("stemp.txt");

    if (inputFile.fail())
        return 0;

    for (size_t i = 0; i < SIZE; i++)
        inputFile >> arr[i].id >> arr[i].credits >> arr[i].cum_gpa;

    inputFile.close();

    cout << "Displaying content:\n\n";

    for (size_t i = 0; i < SIZE; i++)
        printStemp(arr[i], i);

    return 0;
}