从字符串转换为浮点数时丢失文件中的第一行元素

Losing first line element in file when converting from string to float

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

这是我的文件:

###########################
###########################
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 进行转换,但结果是一样的不正确)。

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

将您的内部循环更改为此,以便它处理所有白色space

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

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

            current_pos++;
        }