Read line of numbers using C++

前端 未结 3 1440
再見小時候
再見小時候 2020-12-11 08:23

What\'s the standard way of reading a \"line of numbers\" and store those numbers inside a vector.

file.in
12 
12 9 8 17 101 2 

Should I re

相关标签:
3条回答
  • 2020-12-11 08:58
    #include <vector>
    #include <fstream>
    #include <iterator>
    #include <algorithm>
    
    std::vector<int> data;
    std::ifstream file("numbers.txt");
    std::copy(std::istream_iterator<int>(file), std::istream_iterator<int>(), std::back_inserter(data));
    
    0 讨论(0)
  • 2020-12-11 08:58

    std::cin is the most standard way to do this. std::cin eliminates all whitespaces within each number so you do

    while(cin << yourinput)yourvector.push_back(yourinput)
    

    and they will automatically be inserted to a vector :)

    EDIT:

    if you want to read from file, you can convert your std::cin so it reads automatically from a file with:

    freopen("file.in", "r", stdin)
    
    0 讨论(0)
  • 2020-12-11 09:01

    Here's one solution:

    #include <fstream>
    #include <iostream>
    #include <vector>
    #include <string>
    #include <sstream>
    #include <iterator>
    
    int main()
    {
        std::ifstream theStream("file.in"); 
        if( ! theStream )
              std::cerr << "file.in\n";
        while (true)
        {
            std::string line;
            std::getline(theStream, line);
            if (line.empty())
                break;
            std::istringstream myStream( line );
            std::istream_iterator<int> begin(myStream), eof;
            std::vector<int> numbers(begin, eof);
            // process line however you need
            std::copy(numbers.begin(), numbers.end(),
                      std::ostream_iterator<int>(std::cout, " "));
            std::cout << '\n';
        }
    }
    
    0 讨论(0)
提交回复
热议问题