C++读取成绩文件存二维数组时为何输出指针而非数组内容
问题原因
C未给原生二维数组提供默认的控制台输出重载,直接写cout << grades时,编译器会自动把数组名转换为数组首元素的内存地址,也就是你看到的类指针输出结果,这是C原生数组的固有特性,和你读取文件的逻辑没有关系。
解决方案
你只需要替换掉原代码中直接输出数组的语句,手动循环遍历二维数组的每个元素,按照你需要的格式输出即可,完整可运行的修正代码如下:
#include <iostream> #include <fstream> using namespace std; void read (string filename, double grades[30][5]); int main() { double grades[30][5] = {0.0}; // 初始化数组避免未赋值位置输出乱码 read("grades2.txt", grades); return 0; } void read (string filename, double grades[30][5]){ ifstream input_file(filename); if(input_file.is_open()){ for(int i = 0; i < 30; i++) { for (int j = 0; j < 5; j++) { input_file >> grades[i][j]; } } // 手动实现数组格式输出 cout << "grades [30]{"; for(int i = 0; i < 30; i++) { // 可选择跳过无有效数据的行,不需要可以删除这行判断 if(i > 20 && grades[i][0] == 0 && grades[i][4] == 0) break; if(i != 0) cout << endl; cout << "{"; for(int j = 0; j < 5; j++) { cout << grades[i][j]; if(j != 4) cout << ", "; } cout << "}"; } cout << "}" << endl; } input_file.close(); }
运行上述代码就可以得到你期望的输出格式。
内容的提问来源于stack exchange,提问作者StackOverflowMember
相关产品推荐
相关产品推荐

