C++读取含邻接矩阵的文本文件时首数字丢失、数据读取异常问题
问题描述
你有如下结构的文本数据文件:
6 0,2,0,0,5,0 3,0,4,0,0,0 0,0,0,6,1,0 0,0,0,0,2,0 0,0,0,0,2,4 1,0,0,0,0,0 0,5
数据规则:
- 第一个数字为顶点数
- 接下来的n行n列数据为邻接矩阵
- 最后一行两个数字为起点和终点
你编写了如下C++代码读取数据,但存在三个问题:可以正确获取顶点数,但后续每行第一个数字会被跳过,邻接矩阵数据与文件内容不匹配,最后一行的起点终点无法正常赋值。
void directedGraphAnalysis() { //Open file, read contents, write to graph ifstream file("test2a.txt"); string data = ""; //Each line will be read as a string and converted to an int int nodeCount = 0; int* matrix = nullptr; int matrixIndex = 0; int count = 0; int v1 = INT_MAX; int v2 = INT_MAX; while (getline(file, data, ',')){ int x = stoi(data); ++count; if (count == 1) { nodeCount = x; matrix = new int[nodeCount * nodeCount]; } else if (count < (nodeCount * nodeCount) - 1) { matrix[matrixIndex++] = x; } else if (v1 == INT_MAX) { v1 = x; } else { v2 = x; } cout << "X: " << x << endl; } //DirectedGraph graph = DirectedGraph(matrix, nodeCount); //graph.displayGraph(); cout << "ANALYSIS COMPLETE." << endl; }
问题根因
- 直接使用逗号作为
getline的全局分隔符,不会自动处理换行符。行尾的元素后没有逗号,会和下一行的第一个元素被合并为同一个字符串,导致每行第一个元素被吞、数据错位。 - 边界判断逻辑错误:
count < (nodeCount * nodeCount) - 1的范围不对,会漏掉最后几个矩阵元素,把本该属于矩阵的值赋值给v1/v2。
修复方案
调整读取逻辑,改为逐行读取后再按逗号分割每行的元素,避免换行符干扰,同时修正计数判断逻辑。
修正后代码示例:
#include <fstream> #include <string> #include <sstream> #include <climits> #include <iostream> #include <vector> using namespace std; // 辅助函数:按逗号分割字符串返回数字数组 vector<int> splitLine(const string& line) { vector<int> res; stringstream ss(line); string item; while (getline(ss, item, ',')) { res.push_back(stoi(item)); } return res; } void directedGraphAnalysis() { ifstream file("test2a.txt"); if (!file.is_open()) { cout << "文件打开失败" << endl; return; } string line; int nodeCount = 0; int* matrix = nullptr; int matrixIndex = 0; int v1 = INT_MAX, v2 = INT_MAX; int lineNum = 0; while (getline(file, line)) { if (line.empty()) continue; // 跳过空行 vector<int> nums = splitLine(line); if (lineNum == 0) { // 第一行是顶点数 nodeCount = nums[0]; matrix = new int[nodeCount * nodeCount]; } else if (lineNum <= nodeCount) { // 第2到第n+1行是邻接矩阵行 for (int num : nums) { matrix[matrixIndex++] = num; } } else { // 最后一行是起点终点 v1 = nums[0]; v2 = nums[1]; } lineNum++; } // 测试输出验证 cout << "顶点数:" << nodeCount << endl; cout << "邻接矩阵:" << endl; for (int i = 0; i < nodeCount; i++) { for (int j = 0; j < nodeCount; j++) { cout << matrix[i*nodeCount + j] << " "; } cout << endl; } cout << "起点:" << v1 << ",终点:" << v2 << endl; delete[] matrix; // 记得释放内存 cout << "ANALYSIS COMPLETE." << endl; }
内容的提问来源于stack exchange,提问作者user3308219
相关产品推荐
相关产品推荐

