【问题标题】:How to read txt file into vector and cout the file?如何将txt文件读入vector并cout文件?
【发布时间】:2014-06-09 19:56:16
【问题描述】:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>

using namespace std;


int main()
{
    vector<int> temp;

    ifstream infile;
    infile.open("numbers");

    if (infile.fail())
    {
    cout << "Could not open file numbers." << "\n";
    return 1;
    }

    int data;
    infile >> data;
    while (!infile.eof()) {
    temp.push_back(data);
    infile >> data;
    }

    cout << data << " " << endl;



}

我只是想使用向量从文本文件“数字”中找出所有数字。

15
10
32
24
50
60
25

我的经验几乎为零,关于为什么无法打开的一些指导会非常有帮助。

【问题讨论】:

  • data 在您打印时不在范围内。还有while (!eof()) is wrong..
  • 不是我推荐使用eof,而是按照这个顺序完成,只要不复制最后一个值就可以了。当然,任何其他错误都将被忽略。 data 在打印时看起来也在我的范围内,但在循环之外它只会打印最后一个值。
  • 阅读问题的最后一行和您的其他一些 cmets,您能否澄清您实际遇到的问题?听起来您一开始就无法打开文件。它与可执行文件位于同一目录中吗?你是在 ide 里面运行这个吗?如果是这样,您可能需要将工作目录设置为 numbers 文件所在的位置,以便您的程序找到它。

标签: c++ file vector


【解决方案1】:

您的代码无法正常工作,因为您没有尝试从向量中打印任何内容?

如何打印矢量?

首先您必须了解如何 打印矢量。代码的最后一行,尤其是这一行:

cout << data << " " << endl;

仅打印出文本文件中的最后一个整数。在执行输入的循环中,infile &gt;&gt; data 覆盖了 data 的每个先前值,并将其分配给当前从文件中读取的值。结果是,当循环结束时,data 将等于上次读取的值,尤其是 25 查看您的文件。

operator&lt;&lt;() 没有重载允许您执行类似cout &lt;&lt; temp 的操作,尽管您可以自己实现。有几种打印向量的方法,最简单的是一个简单的循环:

for (unsigned i = 0; i < temp.size(); ++i)
    std::cout << temp[i] << " ";

奖励:打印所有整数的更快方法是从循环内部打印data。 @KerrekSB 也给出了答案。

【讨论】:

    【解决方案2】:

    您的代码很好,但您打印的内容有误。 把main的底部改成这个

    int data;
    while (infile >> data) {
        temp.push_back(data);
    }
    
    for( vector<int>::iterator i = temp.begin(); i != temp.end(); i++) {
        cout << *i << endl;
    }
    

    *在阅读建议的副本后编辑。

    【讨论】:

    • 真的吗?为我编译并运行。
    • 查看建议的欺骗!
    • "'i' 没有命名类型" 我以前没见过 auto。 :S
    • 这是一个 C++11 特性。如果您使用的是 g++ 或 clang++,请使用 -std=c++11 进行编译。
    • 如果我只替换 "cout
    【解决方案3】:

    试试这个:

    #include <fstream>
    #include <iostream>
    #include <iterator>
    #include <vector>
    
    int main()
    {
        std::ifstream infile("data.txt");
    
        if (!infile) { /* error opening file */ }
    
        for (int n : std::vector<int>(std::istream_iterator<int>(infile), {}))
        {
            std::cout << n << '\n';
        }
    }
    

    如果你只想处理数字当然不需要向量:

        for (std::istream_iterator<int> it(infile), end; it != end; ++it)
        {
            std::cout << *it << '\n';
        }
    

    【讨论】:

    • 如果它在纯代码旁边包含一些解释,我会 +1。 OP 显然不知道 istream 迭代器以及为什么在 eof 上迭代不好,仅提及这两个。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-01
    • 2018-08-09
    • 2012-06-17
    相关资源
    最近更新 更多