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

时间:2015-07-27 05:29:37

标签: c++ arrays file storage

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

文本文件可能如下所示

11
hello
1.00
16.0
1.999

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

4 个答案:

答案 0 :(得分:0)

您必须使用fscanf()。阅读文档以获取有关如何使用它的信息。

答案 1 :(得分:0)

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

  1. 一次读取一个由空格分隔成字符串的标记。
  2. 使用以下几种方法之一从字符串中提取浮点数。
  3. 如果提取成功,则处理浮点数。否则,请转到下一个标记。
  4. 以下代码中的某些内容应该有效。

    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.
          }
       }
    }
    

答案 2 :(得分:0)

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

答案 3 :(得分:0)

我使用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
相关问题