尝试使用C++、Ubuntu和MAC……从ASCII文件读取行?

尝试使用C++、Ubuntu和MAC……从ASCII文件读取行?,c++,C++,我有一个ASCII文件students.txt,如下所示忽略空行,它们是我不熟悉此格式化工具的产物: stella 10 4.4 ... peter 1.1 5 ... 也就是说,每行以一个名称开头,后跟一个或多个数字 下面的代码片段旨在逐行读取此文件,将名称读入字符串,将数字读入双精度,依次打印每个文件。当我在Ubuntu上运行它时,它运行得很好,我得到了 stella 10 4.4 peter 1.1 5 但是,当我在Mac上运行它时,会得到以下结果: stella 10 4.4 ter

我有一个ASCII文件students.txt,如下所示忽略空行,它们是我不熟悉此格式化工具的产物:

stella 10 4.4 ...
peter 1.1 5 ...
也就是说,每行以一个名称开头,后跟一个或多个数字

下面的代码片段旨在逐行读取此文件,将名称读入字符串,将数字读入双精度,依次打印每个文件。当我在Ubuntu上运行它时,它运行得很好,我得到了

stella 10 4.4
peter 1.1 5
但是,当我在Mac上运行它时,会得到以下结果:

stella 10 4.4
ter 1.1 5
但是,当我将“彼得”改为“斯佩特”时,效果很好…:

stella 10 4.4
speter 1.1 5
有什么想法吗

#include <iostream>
#include <fstream>
#include <string>

using namespace std;


int main() {

  ifstream infile("students.txt");
  string name;
  double x;

  while ( !infile.eof() ) {
    infile >> name;
    cout << name << ' ';
    while ( infile >> x ){
      cout << x << ' ';
    }
    cout << endl;
    if (! infile.eof() )
      infile.clear();
  }

  return 0;
}

当输入开始分为几行时,通常最容易的方法是逐行读取,然后将其分为几部分:

std::string line;

std::string name;
std::vector<double> values;

while (std::getline(infile, line)) {
    std::istringstream buffer(line);
    double temp;

    buffer >> name;
    while (buffer >> temp)
        values.push_back(temp);
}
我特别感兴趣的是,为什么我的代码片段在linux和mac上会产生不同的结果

我认为这种行为是由于Libc++和Libstdc++在输入流中处理浮点输入的方式不同,而不是Mac和Ubuntu

<> p>您最有可能使用的是LIGB+LLVM/CLAN标准的C++库,因为在Linux中标准的C++库是标准的。 在这种情况下,Libc++将吃掉任何可能转换为double的字符,而Libstdc++则不会。例如,它吃掉peter中的pe,因为p和e可能是double表示的一部分

例如,如果您的students.txt如下所示:

0x1a 90.2 84.3
0x1a 1.5 56.4
当您使用Libstdc++编译原始程序并运行它时,您会得到:

0x1a 90.2 84.3 0 
x1a 1.5 56.4
使用Libc++编译并运行时,会提供:

0x1a 90.2 84.3 26 1.5 56.4
Libc++将0x1a识别为十六进制数26,而Libstdc++仅转换0x1a中的0,并将x1a解析为字符串名


有关更详细的解释(包括示例),请参见

FYI感谢您的回复;然而,我特别感兴趣的是,为什么我的代码片段在linux和mac上会产生不同的结果…:o@Marco:我的第一个猜测是,你在Mac上使用的库只是有一个bug。