将文件解析为3个独立的数组

Parsing a file into 3 separate arrays

本文关键字:独立 数组 3个 文件      更新时间:2024-05-24

我想知道如何解析字符串,这样我就可以将第一个数字存储到一个双数组中,将第二个数字存储在一个单独的双数组中;输入的格式为:

Los Angeles 31.00 40.10
Miami 108.12 20.11
Nashville 44.33 25.99

它们被一个单独的空间隔开,每个带坐标的城市名称都被逐行隔开。我只想用空白和换行来分割字符串,但有些城市(如洛杉矶(在两者之间有一个空格。我如何将它们全部放入各自的string[]double[]阵列中?我想不出办法加上";洛杉矶";转换成字符串数组而不是"0";Los";以及";Angeles";

一种选择是在下一个标记不是双引号的情况下继续添加到字符串中。从本质上讲,你会提取下一个";字符串";,并测试它是否是替身。如果是,那么您将把流的位置回滚到读取最后一个字符串之前,并继续解析doubles。否则,您将继续添加字符串。

对于一行,你可能可以做这样的事情。注意:这假设您想要获得所有单词,直到达到双精度,所以如果您有两个相邻的字符串字段,其中第一个和第二个可以包含空格,这将不起作用。

ifstream filein("path");
for(int i = 0; filein; i++) //each line of the file
{
std::string line;
getline(filein, line); //use getline to safely get the next line
std::stringstream lineStream(line); //create a stream to extract from
//assuming cities is the string array, and i is a loopvar
cities[i] = extractUntilDouble(lineStream);
//can now get the other properties from lineStream
}

其中以下功能被定义为

std::string extractUntilDouble(const std::istream & filestream)
{
std::string toReturn="";
std::string token="";

std::streampos fallbackPosition; //used since we will take one extra chunk 
//than we should at the end, want the caller to be able to extract that
do
{
toReturn += token;
fallbackPosition = filestream.tellg(); //save position before extracting
filestream >> token;
} while (!isNumeric(token)); //check if this token is a number
filestream.seekg(filestream); //go back to the last token

}
bool isNumeric(const string& str)
{
return str.find_first_not_of("0123456789.") == std::string::npos;
}

这可能不是最有效或最优雅的方法,但却是一个潜在的解决方案。您也可以覆盖全局>gt;字符串运算符可以做到这一点,使用甜蜜的插入语法并避免额外显式的方法调用,但这当然可能会在以后导致意外行为。。。