(C++) Reading digits from text file

后端 未结 2 444
囚心锁ツ
囚心锁ツ 2021-01-07 09:57

I have a text file which looks like this:

73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85

相关标签:
2条回答
  • 2021-01-07 10:34

    There are several ways to accomplish what you are looking for, in this post I'll describe three different methods. All three of them assume that you open your file using an std::ifstream ifs ("filename.txt") and that your "array" is actually a vector declared as std::vector<int> v.

    At the end of this post there is also a little advice on how to speed up insertion into your vector.


    I'd like to keep it simple..

    The most simple approach is to read one char at a time using operator>> and then subtract '0' from the value returned.

    The standard guarantee that '0' through '9' are sequential, and since a char is nothing but a numeric value printed in a different matter it can implicitly be casted to int.

    char c;
    
    while (ifs >> c)
      v.push_back (c - '0');
    

    I love the STL, and hate writing loops..

    This will by many be treated as the "c++ way to do it", espacially if you are talking to STL-fanboys, though it requires a lot more code to write..

    #include <algorithm>
    #include <functional>
    #include <iterator>
    
    ...
    
    std::transform (
      std::istream_iterator<char> (ifs),
      std::istream_iterator<char> (), 
      std::back_inserter (v),
      std::bind2nd (std::minus<int> (), '0')
    );
    

    I don't want to write loops, but why not use a lambda? c++11

    #include <algorithm>
    #include <functional>
    #include <iterator>
    
    ...
    
    std::transform (
      std::istream_iterator<char> (iss),
      std::istream_iterator<char> (),
      std::back_inserter (v),
      [](char c){return c - '0';}
    );
    

    Will my std::vector reallocate storage upon each insertion?

    Yes, probably. To speed things up you can reserve storage in your vector before you start doing any insertions, as in the below.

    ifs.seekg (0, std::ios::end); // seek to the end of your file
    v.reserve (ifs.tellg ()    ); // ifs.tellg () -> number of bytes in it
    ifs.seekg (0, std::ios::beg); // seek back to the beginning
    
    0 讨论(0)
  • 2021-01-07 10:35
    char digit;
    std::ifstream file("digits.txt");
    std::vector<int> digits;
    // if you want the ASCII value of the digit.
    1- while(file >> digit) digits.push_back(digit);
    // if you want the numeric value of the digit.
    2- while(file >> digit) digits.push_back(digit - '0'); 
    
    0 讨论(0)
提交回复
热议问题