繁体   English   中英

在C ++中解析.dat文件

[英]Parse a .dat file in c++

我有一个.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

当我调试时,我看到字符串向量应该是正确的,但是当我打印向量时,即使我将其打印为矢量,它也会在矢量的元素之间留有空格

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);


    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM