gpt4 book ai didi

c++ - 在 C++ 中解析 .dat 文件

转载 作者:太空宇宙 更新时间:2023-11-04 11:36:06 26 4
gpt4 key购买 nike

我有一个 .dat 文件,但每一行都不同。我的意思是有一行 double 和一行字符串。

我可以读取文件,甚至可以解析它,但是字符串出了点问题。如果我有一行只有“A”作为字符串,它会给我带空格的字符串。我不知道出了什么问题,但这是

我的代码:

ifstream file;
file.open(name,ios::in|ios::binary);
vector<string> strings;
string line;

if (file.is_open())
{
while(file.good())
{
vector<double> vdoubles;

getline(file,line,'\n');
stringstream ss(line);

double num= 0.0;
string str = ss.str();

if (! (ss >> num)) // if this is a string and not double
{
strings.push_back(str);
}
else
{
do
{
vdoubles.push_back(num);
}while ( ss >> num);


}
}
}

.dat 文件示例:

A
0.02 0.4 0.6
BC
0.45 0.5 0.8

当我调试时,我看到了字符串 vector ,但当我打印该 vector 时,它在 vector 元素之间打印了空格,即使我将它打印为

for (int i = 0; i < strings.size(); i++)
cout << strings[i];
cout << endl;

那为什么它也给我空格呢?

最佳答案

好的,所以答案是您不能使用相同的字符串流来解析不同的类型。所以这就是解决方案

    if (! (ss >> num)) // if this is a string and not double
{
stringstream l;
l << line;
l >> str;
strings.push_back(str);
}
else
{
do
{
vdoubles.push_back(num);
}while ( ss >> num);


}

关于c++ - 在 C++ 中解析 .dat 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23022246/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com