【问题标题】:reading pairs of data from a file从文件中读取数据对
【发布时间】:2017-05-01 06:53:16
【问题描述】:

我正在尝试使用以下代码从文件中读取数据对。

#include <iostream>
#include <fstream>
#include <vector>


using namespace std;

int main()
{
//**** Opening data file ****   

    ifstream infile;
    infile.open("reg_data_log.inp");

    if (infile.is_open())
    {
        cout << "File successfully open" << endl;

    }
    else
    {
    cout << "Error opening file";
    }

//**** Reading data ***

    vector<pair<double, double> > proteins;

    pair<double, double> input;

    while (infile >> input.first >> input.second) 
    {
        proteins.push_back(input);
    }

//**** Show data in screen ****

    cout << "Proteins analized: " << proteins.size() << endl;

    for(unsigned int i=0; i<proteins.size(); i++)
    {
        cout << i.first << ", " << i.second << endl;
    }

}

编译时出现以下信息

“65:13:错误:请求‘i’中的成员‘first’,它是非类类型‘unsigned int’”
“65:13: 错误:请求‘i’中的成员‘first’,它是非类类型‘unsigned int’”

我无法解决这个问题。有人可以帮忙吗?

【问题讨论】:

  • 错误很明显。您在最后一个循环中使用i。这是一个int。然而你尝试访问i.first
  • 您需要使用迭代器。例如:for (auto i : proteins) {cout &lt;&lt; i.first &lt;&lt; ", " &lt;&lt; i.second &lt;&lt; endl;}
  • 迭代器给我一个编译器错误 63:7:警告:'auto' 在 C++11 中改变了含义;请删除它[-Wc++0x-compat]
  • @berkboy 你在使用 pre c++11 编译器吗?
  • 重新。 “‘auto’改变含义”:升级你的编译器或使用-std=c++11编译标志(如果它很旧,在你的版本中可能是-std=c++0x)。

标签: c++ vector std-pair


【解决方案1】:

进一步查看你的循环

for(unsigned int i=0; i<proteins.size(); i++)
{
    cout << i.first << ", " << i.second << endl;
}

您正试图访问整数值i 的属性first。整数没有该属性,它是 pair 对象的属性。

我认为您对使用迭代器和索引进行迭代感到困惑。简单的解决方法是使用基于范围的 for 循环,正如 cmets 中所建议的那样。

for(auto d: proteins)
{
    cout << d.first << ", " << d.second << endl;
}

现在你所拥有的是向量中的元素,而不是整数。您现在可以访问firstsecond

如果你不能使用基于范围的for循环和auto,那么你可以使用旧的迭代器for循环方式。

for(vector<pair<double, double> >::iterator it = proteins.begin();
    it != proteins.end();
    ++it)
{
    cout << it->first << ", " << it->second << endl;
}

并且其他人已经发布了如何使用索引来完成它,所以我不会在这里重复。

【讨论】:

  • 感谢您的解释。我明白我的错误了。
【解决方案2】:

正如John Mopp 在他的评论中提到的那样,实际上您引用的是 int 而不是 pair-type。以下循环很可能会解决您的问题:

cout << "Proteins analized: " << proteins.size() << endl;

for(unsigned int i=0; i<proteins.size(); i++)
{
    cout << proteins[i].first << ", " << proteins[i].second << endl;
}

我还没有对此进行测试,但我非常确信这可以解决您的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-27
    相关资源
    最近更新 更多