从字符串转换为float时丢失文件中的第一行元素[关闭]

问题描述 投票:-3回答:1

我有以下问题,我不知道为什么以及它是如何发生的。

这是我的档案:

###########################
###########################
POINTS
68.252 87.2389 -50.1819
68.2592 87.2451 -50.2132
68.2602 87.2436 -50.2133
68.2564 87.2333 -50.1817
68.2618 87.2475 -50.244
68.2476 87.2446 -50.182
68.2582 87.2466 -50.2131
68.2618 87.2475 -50.244
67.9251 87.2509 -49.8313
67.9311 87.2511 -49.8443
67.9786 87.196 -49.8365
67.9735 87.1946 -49.8231
67.9383 87.2513 -49.8574
67.9848 87.1975 -49.8499
68.0704 87.0819 -49.8067
68.0778 87.09 -49.8349
68.0002 87.2009 -49.8769
68.088 87.1 -49.8633
68.1689 86.9755 -49.8051
68.1709 86.9825 -49.8199
68.1672 86.9693 -49.7903
68.2164 86.9204 -49.7972
68.2157 86.913 -49.7821
...
END
##############################
TRIANGLES
...

我想要的是读取我的文件的每一行。在空格上拆分并将字符串转换为浮点数。这就是我这样做的方式:

#include "pch.h"
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>

using namespace std;

int main()
{
    string line;

    ifstream inFile;
    string path = "C:\\...";
    inFile.open(path);

    if (!inFile)
    {
        cerr << "Unable to the open file.";
        exit(1);
    }

阅读我的文件的基本步骤

    int vc_size = numOfPoints(inFile); // A function I implemented to get the number of points

    vector<float> my_coordinates(vc_size);

    int current_pos = 0;

初始化一些变量

    while (getline(inFile, line))
    {
        if (line == "POINTS")
        {
            while (getline(inFile, line, ' '))
            {
                if (line == "END" || current_pos >= vc_size)
                    break;

                my_coordinates[current_pos] = atof(line.c_str());

                current_pos++;
            }
        }
    }

    inFile.close();

    for (size_t i = 0; i < vc_size; ++i)
        cout << my_coordinates[i] << endl;

    return 0;
}

虽然这似乎合乎逻辑,但我有一个很大的问题。我所有行的第一个值(第一个除外)都消失了(意味着所有的68.something都不在我的输出中)。而更令人困惑的是,如果我让我的vector成为vector<string>并做x_coordinates[current_pos] = line;,那么代码就可以了。这对我没有任何意义,因为改变的唯一步骤是从stringfloat的转换(我试图使用stringstream进行转换,但这是不正确的结果)。

c++ vector readfile
1个回答
1
投票

问题是您的代码只将空间作为数字的分隔符,但实际上您有空格和换行符作为分隔符。

将内循环更改为此,因此它处理所有空格

        string item;
        while (inFile >> item)
        {
            if (item == "END" || current_pos >= vc_size)
                break;

            x_coordinates[current_pos] = atof(item.c_str());

            current_pos++;
        }
© www.soinside.com 2019 - 2024. All rights reserved.