从文件中读取浮点数/单词/符号,并仅将浮点数存储在数组中

Reading floats/words/symbols from a file and ONLY storing the floats in an array C++

本文关键字:浮点数 存储 数组 符号 文件 读取 单词      更新时间:2023-10-16

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

文本文件可能看起来像这样

<>之前11你好1.0016.01.999之前

我知道如何打开文件;它只是抓取只有浮动我挣扎。

您必须使用fscanf()

只要你不介意把整数当作浮点数,比如你的文章中的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.
      }
   }
}

我会使用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];
    }
};

然后使用该facet向流中注入区域设置,然后读取数字:

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
// 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(); 
}