将.txt文件读取到c++流中,一些字符串由两个单独的单词组成



对于一个大学项目,我必须将.txt文件中描述的地铁网络读取到由节点和边组成的图中,到目前为止,我已经能够读取该文件并自动检查字符串、doubles或int。现在的问题是,一些站名由两个单独的单词组成,我的代码将进一步跳到描述距离或时间的double或int值,并将其视为站名的第二个字符串。

以下是描述格式的.txt文件的摘录:

U1 Warschauer Str -> Schlesisches Tor: 0,8 2
U1 Schlesisches Tor -> Gourlitzer Bahnhof: 0,9 2
U2 Pankow -> Vinetastrasse: 0,5 1
Line Station 1 -> Station2: Distance_in_km Travel_time_in_minutes 
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
int main()
{
std::ifstream datei("C:\Users\jeff\Desktop\Fortgeschrittene Algorithmen & Programmierung\Berlin.txt");
std::string zeile;
while (std::getline(datei, zeile))
{
for (int i = 0; i < zeile.size(); i++)
{
if (zeile[i] == ',')
{
zeile[i] = '.';
};
if (zeile[i] == '-' || zeile[i] == '>')
{
zeile[i] = ' ';
};

if (zeile[i] == ':')
{
zeile[i] = ' ';
};

}

std::stringstream ausgabe(zeile);
std::string linie, station1a, station1b, station2a, station2b;
double c;
int d;
ausgabe >> linie >> station1a >> station1b >> station2a >> station2b >> c >> d;
std::cout << "Linie : " << linie << " StationsnameSource : " << station1a << " " << station1b << " StationsnameDestination : " << station2a << " " << station2b << " Entfernung in km : " << c << " Fahrtdauer in min :  " << d << "n";
enter code here


}

return 0;
}

我为车站名称制作了四个字符串,但是,如果车站只有一个名称,它将使用下一个字符串,并仅使用该字符串(例如,第二个车站的字符串名称或用于距离的双重名称(

有人知道如何解决这个问题吗?非常感谢您的帮助。

向您展示原理的粗代码。

输入文件,train.txt:

U1 Warschauer Str -> Schlesisches Tor: 0,8 2
U1 Schlesisches Tor -> Gourlitzer Bahnhof: 0,9 2
U2 Pankow -> Vinetastrasse: 0,5 1

输出:

Station1=U1 Warschauer Str , Station2=Schlesisches Tor
Station1=U1 Schlesisches Tor , Station2=Gourlitzer Bahnhof
Station1=U2 Pankow , Station2=Vinetastrasse

这需要调整,但你会得到这样的想法:

#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream ifs;
string buf;
int index, startIndex, n;
char station1[36];
char station2[36];
ifs.open("train.txt", ifstream::in);
while (getline(ifs, buf))           // Get characters into string, discard newline
{
//
// Search for first station terminated by ->
//
index = 0;
while (buf[index] != '-')
{
index++;
if (buf[index] == '>')
break;
}
//
// Get first station
//
strncpy(station1, buf.c_str(), index);
station1[index] = '';
index += 3; // Past "-> "
//
// Search for next (last) station terminated by :
//
startIndex = index;
while (buf[index] != ':')
index++;
//
// Get next (last) station
//
n = index - startIndex;
strncpy(station2, buf.c_str() + startIndex, n);
station2[n] = '';
printf("Station1=%s, Station2=%sn", station1, station2);
}
ifs.close();
return 0;
}

最新更新