【问题标题】:Reading floats/words/symbols from a file and ONLY storing the floats in an array C++从文件中读取浮点数/单词/符号并仅将浮点数存储在数组 C++ 中
【发布时间】:2015-07-27 05:29:36
【问题描述】:

我有一个 C++ 编程问题,我被要求从一个包含多个浮点数、单词和符号(例如 # ! %)的文件中读取该问题。从这个文件中,我必须只取浮点数并将其存储到一个数组中。

文本文件可能如下所示

11 你好 1.00 16.0 1.999

我知道如何打开文件;它只是抓住我正在挣扎的花车。

【问题讨论】:

  • 这些类型是按特定顺序排列的还是随机的?
  • 当您读取文件时,您将获得 char* 的所有内容。可能是你需要 try { auto long_val = std::stol(input); } catch(...){} ,如果它通过它的 long 值否则不是。
  • 您可能想澄清11 是否为浮点数。另外,请将您的代码添加到您的问题中 - 有几种方法可以在 C++ 中读取文件,很高兴知道您使用的是哪一种。

标签: c++ arrays file storage


【解决方案1】:

你必须使用fscanf()。阅读文档以了解如何使用它。

【讨论】:

    【解决方案2】:

    只要不介意将整数视为浮点数,例如帖子中的11,可以使用以下策略。

    1. 一次将一个以空格分隔的标记读入一个字符串。
    2. 使用多种方法之一从字符串中提取浮点数。
    3. 如果提取成功,则处理浮点数。否则,请转到下一个令牌。

    下面的代码应该可以工作。

    std::string token;
    std::ifstream is(filename); // Use the appropriate file name.
    while ( is >> token )
    {
       std::istringstream str(is);
       float f;
       if ( str >> f )
       {
          // Extraction was successful.
          // Check whether there is more data in the token.
          // You don't want to treat 11.05abcd as a token that represents a
          // float.
          char c;
          if ( str >> c )
          {
             // Ignore this token.
          }
          else
          {
             // Process the float.
          }
       }
    }
    

    【讨论】:

      【解决方案3】:

      我会使用 ctype facet 将除数字之外的所有内容分类为空格:

      struct digits_only : std::ctype<char>
      {
          digits_only() : std::ctype<char>(get_table()) {}
      
          static std::ctype_base::mask const* get_table()
          {
              static std::vector<std::ctype_base::mask>
                  rc(std::ctype<char>::table_size, std::ctype_base::space);
      
              if (rc['0'] == std::ctype_base::space)
                  std::fill_n(&rc['0'], 9, std::ctype_base::mask());
              return &rc[0];
          }
      };
      

      然后使用该方面为流注入区域设置,然后读取您的数字:

      int main() {
          std::istringstream input(R"(
      11
      
      hello
      
      1.00
      
      16.0
      
      1.999)");
      
          input.imbue(std::locale(std::locale(), new digits_only));
      
          std::copy(std::istream_iterator<float>(input), std::istream_iterator<float>(),
              std::ostream_iterator<float>(std::cout, "\t"));
      }
      

      结果:

      11      1       16      1.999
      

      【讨论】:

        【解决方案4】:
        // reading a text file and storing only float values
        #include <iostream>
        #include <fstream>
        #include <string>
        #include <sstream>
        
        using namespace std;
        
        int main () {
          string line;
          ifstream myfile ("example.txt");
          std::vector<float> collection;
        
          if (myfile.is_open())
          {
            while ( getline (myfile,line) )
            {
              if(checkIfFloatType(line))
              {
                 collection.push_back(std::stof (line));
              }
            }
            myfile.close();
          }
        
          else cout << "Unable to open file"; 
        
          return 0;
        }
        
        bool checkIfFloatType( string str ) {
            std::istringstream iss(str);
            float f;
            iss >> noskipws >> f;
            return iss.eof() && !iss.fail(); 
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-10-19
          • 2011-02-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多