How To Parse String File Txt Into Array With C++

前端 未结 3 1451
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-03 09:29

I am trying to write a C++ program, but I am not familiar with C++. I have a .txt file, which contains values as follows:

0
0.0146484
0.0292969
         


        
3条回答
  •  时光说笑
    2021-01-03 09:37

    Assuming you want your data stored as floating point numbers (not strings) you probably want to do something like this:

    #include 
    #include 
    #include 
    #include 
    
    int main() { 
        std::ifstream in("Qi.txt");
    
        // initialize the vector from the values in the file:
        std::vector lines{ std::istream_iterator(in),
                                   std::istream_iterator() };
    
        // Display the values:
        for (int i=0; i is preferable to std::ifstream in; in.open("Qi.txt");. Likewise, it's preferable to initialize the vector of lines directly from istream iterators rather than create an empty vector, then fill it in an explicit loop.

    Finally, note that if you insist on writing an explicit loop anyway, you never want to use something like while (somestream.good()) or while (!somestream.eof()) to control your loop -- these are mostly broken, so they don't (dependably) read a file correctly. Depending on the type of data involved, they'll frequently appear to read the last item from the file twice. Usually, you want something like while (file >> value) or while (std::getline(file, somestring)). These check the state of the file immediately after reading, so as soon as reading fails they fall out of the loop, avoiding the problems of the while (good()) style.

    Oh, as a side note: this is written expecting a compiler that (at lest sort of) conforms with C++11. For an older compiler you'd want to change this:

        // initialize the vector from the values in the file:
        std::vector lines{ std::istream_iterator(in),
                                   std::istream_iterator() };
    

    ...to something like this:

        // initialize the vector from the values in the file:
        std::vector lines(( std::istream_iterator(in)),
                                    std::istream_iterator() );
    

提交回复
热议问题