【问题标题】:Parsing a file into 3 separate arrays将文件解析为 3 个单独的数组
【发布时间】:2021-07-01 20:43:39
【问题描述】:
我想知道如何解析一个字符串,例如我将第一个数字存储到一个双精度数组中,第二个数字存储到一个单独的双精度数组中,其余的字符串也存储在它自己的单独数组中;输入的格式为:
Los Angeles 31.00 40.10
Miami 108.12 20.11
Nashville 44.33 25.99
它们由一个空格分隔,每个城市名称和坐标是逐行分隔的。我只想用空格和换行符分割字符串,但有些城市(如洛杉矶)之间有空格。如何将这些全部放入各自的 string[] 和 double[] 数组中?如果不是“Los”和“Angeles”,我想不出一种将“Los Angeles”添加到字符串数组中的方法
【问题讨论】:
标签:
c++
string
parsing
split
【解决方案1】:
一个选项是在下一个标记不是双精度时继续添加到字符串中。本质上,您将提取下一个“字符串”,并测试它是否为双精度。如果是,那么您将在读取最后一个字符串之前将流的位置回滚,并继续解析双精度数。否则,您将继续添加字符串。
对于单行,您也许可以做这样的事情。注意:这假设您想要获取所有单词,直到您点击双精度,因此如果您有两个相邻的字符串字段,其中第一个和或第二个可能包含空格,这将不起作用。
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;
}
这可能不是最有效或最优雅的方式,而是一种潜在的解决方案。您还可以覆盖全局 >> 字符串运算符来执行此操作,以使用这种甜蜜的插入语法并避免额外显式的方法调用,但这当然可能会导致以后出现意外行为......