如何打印一个元组的向量?

3

我正在尝试创建一个包含两个整数元组的向量,并从文本文件中获取这些整数。为了确保我拥有想要的向量,我尝试打印我的内容,但输出没有显示任何内容。我不确定是因为我的代码还是因为我放置文本文件的位置。我现在被卡住了。如果有任何帮助,我会非常感激。谢谢。

using namespace std;


int main()
{
ifstream file("source.txt");
typedef vector<tuple<int, int>> streets;
streets t; 
int a, b;

if (file.is_open()) 
{
    while (((file >> a).ignore() >> b).ignore())
    {
        t.push_back(tuple<int, int>(a, b));
        for (streets::const_iterator i = t.begin();i != t.end();++i)
        {
            cout << get<0>(*i) << endl;
            cout << get<1>(*i) << endl;
        }
        cout << get<0>(t[0]) << endl;
        cout << get<1>(t[1]) << endl;                   
    }
}

file.close();

system("pause");
return 0;

这是我的文本文件和它的位置。 查看图片描述 如果需要,这是我的调试输出结果。 查看调试输出

1
你可以一次打印一个元组。使用调试器有助于找出循环为什么不起作用吗? - Scott Hunter
你检查过文件是否已经正确打开了吗?file.is_open()返回的是true吗? - BobMorane
你是指输出窗口中显示的内容吗?因为我看了一下,但是没有完全理解它。如果你想看的话,我只是把它放在了我的问题里。 - Damonlaws
那么我真的不需要那个while循环吗?因为我认为它只是查看元组中的第一个整数并忽略下一个整数,以此类推。 - Damonlaws
1个回答

1
你应该使用循环,每次打印一个元组。
完整的最小示例:
#include <iostream>
#include <tuple>
#include <vector>
#include <fstream>
using namespace std;

int main(void) {
    std::ifstream infile("source.txt");
    vector<tuple<int, int>> streets;
    int a, b;
    while (infile >> a >> b)
    {
        streets.push_back(tuple<int, int>(a, b));
    }
    infile.close();
    for(auto& tuple: streets) {
        cout << get<0>(tuple) << " " << get<1>(tuple) << endl;   
    }
    return 0;
}

输出:

1 2
3 4
5 6
7 8

看起来不错。如果我想从文本文件中获取整数怎么办? - Damonlaws
@Damonlaws,那是一个完全不同的问题,你觉得呢? - n0rd
@Damonlaws n0rd是正确的,但由于您是新来的,我更新了我的问题,并回答了您的问题。请不要忘记接受答案并遵循n0rd的建议,一次只提一个问题。 - gsamaras

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接