Read line of numbers using C++

前端 未结 3 1441
再見小時候
再見小時候 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 09:01

    Here's one solution:

    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    
    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 begin(myStream), eof;
            std::vector numbers(begin, eof);
            // process line however you need
            std::copy(numbers.begin(), numbers.end(),
                      std::ostream_iterator(std::cout, " "));
            std::cout << '\n';
        }
    }
    

提交回复
热议问题