C++ 无法显示第一列

C++ 无法显示第一列,c++,C++,您好,我刚从一个文件中获取了一些数据,但这非常奇怪,因为我无法获取文本文件的第一列。这是我的文本文件: 1.2 2.6 3.5 1.02 3.05 4.65 7.15 0.54 9.26 这是我的密码: #include <iostream> #include <fstream> int main() { std::ifstream myFile("a.txt"); std::string line; while(std::getline(myFile

您好,我刚从一个文件中获取了一些数据,但这非常奇怪,因为我无法获取文本文件的第一列。这是我的文本文件:

1.2 2.6 3.5
1.02 3.05 4.65
7.15 0.54 9.26 
这是我的密码:

#include <iostream>
#include <fstream>

int main() {
  std::ifstream myFile("a.txt");
  std::string line;

  while(std::getline(myFile, line)) {
    std::string col1, col2, col3;
    myFile >> col1, col2 >> col3;
    std::cout << col1 << " " << col2 << " " << col3 << std::endl;
  }

  return EXIT_SUCCESS;
}
相反,我看到的是:

1.02 3.05 4.65
7.15 0.54 9.26 

多谢各位

我建议使用
操作员>>
输入数据:

double col1, col2, col3;
char comma;
while (myFile >> col1)
{
  myFile >> comma;
  myFile >> col2 >> comma;
  myFile >> col3;
  //...
}
更好的方法是使用以下结构对输入行建模:

struct Record
{
  double value1;
  double value2;
  double value3;
  friend std::istream& operator>>(std::istream& input, Record& r);
};

std::istream& operator>>(std::istream& input, Record& r)
{
  char comma;
  input >> r.value1 >> comma;
  input >> r.value2 >> comma;
  input >> r.value3;
  return input;
}
上述代码允许您读取如下文件:

std::vector<Record> database;
Record r;
while (myFile >> r)
{
  database.push_back(r);
}
std::向量数据库;
记录r;
while(myFile>>r)
{
数据库。推回(r);
}
要在文件中读取的代码片段不依赖于数据的格式,可以用于以其他格式读取。记录的结构决定了数据的输入方式。

Getline()和>>

问题是您使用
getline()
检查输入,然后尝试使用
>
从流中读取数据。这不符合预期

想象一下,它是流中的某种光标。
std::fstream
的成员函数可以移动此光标,其他函数则不能

使用
getline()
向前移动光标。当您使用
>
时,光标已经过了您想要得到的位置

有一些解决办法。最简单的是

int main(){
    std::ifstream myFile("a.txt");
    std::string line;
    std::string col1, col2, col3;
    while(myFile >> col1 >> col2 >> col3){
        std::cout << col1 << " " << col2 << " " << col3 << std::endl;
    }
return EXIT_SUCCESS;
}
我的编译器
Apple LLVM 8.1.0版(clang-802.0.38)
甚至不允许这样做。(复制)所以我想您应该像这样使用逗号运算符

 myFile >> (col1, col2) >> col3;
逗号运算符执行以下操作:如果对
expression1,expression2
expression1
进行求值,则对
expression2
进行求值,并将
expression2
的结果作为整个表达式
expression1,expression2
的结果返回

让我们检查一下
>
是如何协同工作的。你可以看到,<> > >代码>绑定比<代码>强,(实际上,是所有C++运算符最弱的优先级)。 这意味着

myFile >> (col1, col2) >> col3;
          ^^^^^^^^^^^^
          result is col2
具有与相同的效果

myFile >> col2 >> col3;
因此,
col1
未使用。我的编译器(使用
-Wall-Wpedantic
)给出警告

表达式结果未使用[-Wunused值]


您有一个逗号,这可能是问题所在,需要将其更改为
col1>>col2
首先从文件中删除
getline()
,忽略该行,然后继续读取其他变量。如果不希望第一行消失在
变量中,请不要调用
getline()
 myFile >> (col1, col2) >> col3;
myFile >> (col1, col2) >> col3;
          ^^^^^^^^^^^^
          result is col2
myFile >> col2 >> col3;