Read integers from file - line by line

前端 未结 4 1062
遥遥无期
遥遥无期 2020-12-11 20:07

How can I read integers from a file to the array of integers in c++? So that, for example, this file\'s content:

23
31
41
23

would become:<

相关标签:
4条回答
  • 2020-12-11 20:44
    std::ifstream file_handler(file_name);
    
    // use a std::vector to store your items.  It handles memory allocation automatically.
    std::vector<int> arr;
    int number;
    
    while (file_handler>>number) {
      arr.push_back(number);
    
      // ignore anything else on the line
      file_handler.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }
    
    0 讨论(0)
  • 2020-12-11 20:44

    You can just use file >> number for this. It just knows what to do with spaces and linebreaks.

    For variable-length array, consider using std::vector.

    This code will populate a vector with all numbers from a file.

    int number;
    vector<int> numbers;
    while (file >> number)
        numbers.push_back(number);
    
    0 讨论(0)
  • 2020-12-11 20:47

    Here's one way to do it:

    #include <fstream>
    #include <iostream>
    #include <iterator>
    
    int main()
    {
        std::ifstream file("c:\\temp\\testinput.txt");
        std::vector<int> list;
    
        std::istream_iterator<int> eos, it(file);
    
        std::copy(it, eos, std::back_inserter(list));
    
        std::for_each(std::begin(list), std::end(list), [](int i)
        {
            std::cout << "val: " << i << "\n";
        });
        system("PAUSE");
        return 0;
    }
    
    0 讨论(0)
  • 2020-12-11 20:58

    don't use array use vector.

    #include <vector>
    #include <iterator>
    #include <fstream>
    
    int main()
    {
        std::ifstream      file("FileName");
        std::vector<int>   arr(std::istream_iterator<int>(file), 
                               (std::istream_iterator<int>()));
                           // ^^^ Note extra paren needed here.
    }
    
    0 讨论(0)
提交回复
热议问题