我正在开发一个从输入文件中读取道路数据的程序,如下所示:
INTERSECTIONS:
1 0.5 Speedway and Campbell // intersection ID, safety rating, name
2 0.3 Park and Grant
3 0.1 Euclid and Grant
STREETS:
1 2 3 // intersection 1, intersection 2, distance in between
2 3 1
3 1 2
表中的每个值都由制表符 (\t) 字符分隔
我必须将这些数据读入图表指定的适当变量中。我主要是在寻找一个简单的答案:是否可以使用 getline 一次读取一行,然后将该行分成每一位数据?如果是这样,我会怎么做?
到目前为止,这是我在主文件中的内容:
#include "graph.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
vector <Vertex*> vertices;
vector <Edge*> edges;
int main (int argc, char *argv[]) {
if( argc != 4 )
{
std::cout << "\nUsage: " << argv[0] << " distanceInMiles startingIntersection streetMapGraphFile \n\n" << endl;
return -1;
}
ifstream mapfile ("streetMapGraphFile");
int count = 0;
int loc = 0;
Graph streetMap;
if (mapfile.is_open())
{
while ( mapfile.good() )
{
while ( count != 1 ) {
string line;
getline(mapfile,line);
if ( line == "INTERSECTIONS:" )
{
getline(mapfile,line);
}
else if ( line == "" )
{
count++;
break; // to avoid reading blank line line
}
stringstream ss(line);
ss >> streetMap.intersection->streetID >> streetMap.intersection->safetyIndex;
getline(ss, streetMap.intersection->name);
}
string line2;
getline(mapfile,line2);
if ( line2 == "STREETS:" )
{
getline(mapfile,line2);
}
// TODO: Read in the edges/streets here
stringstream ss2(line2);
ss2 >> streetMap.street->intersection1 >> streetMap.street->intersection2 >> streetMap.street->distance;
}
mapfile.close();
}
else { cerr << "Error: unable to open file" << endl; }
return 0;
}
我已经更改了代码以在行字符串上实现 stringstream,但是当我逐步调试时,我的编译器在执行此行后崩溃:
ss >> streetMap.intersection->streetID >> streetMap.intersection->safetyIndex;
错误显示“safejogger.exe 中 0x0F592208 (msvcp110d.dll) 处的未处理异常:0xC0000005:访问冲突写入位置 0xCCCCCCCC。”