【问题标题】:Read floats from a .txt file从 .txt 文件中读取浮点数
【发布时间】:2012-01-15 07:26:15
【问题描述】:

如何从 .t​​xt 文件中读取浮点数。根据每行开头的名称,我想读取不同数量的坐标。浮点数由“空格”分隔。

示例:triangle 1.2 -2.4 3.0

结果应该是: float x = 1.2 / float y = -2.4 / float z = 3.0

该文件有更多不同形状的线条,可能更复杂,但我想如果我知道如何做其中一个,我可以自己做其他的。

到目前为止我的代码:

#include <iostream>

#include <fstream>

using namespace std;

int main(void)

{

    ifstream source;                    // build a read-Stream

    source.open("text.txt", ios_base::in);  // open data

    if (!source)  {                     // if it does not work
        cerr << "Can't open Data!\n";
    }
    else {                              // if it worked 
        char c;
        source.get(c);                  // get first character

        if(c == 't'){                   // if c is 't' read in 3 floats
            float x;
            float y;
            float z;
            while(c != ' '){            // go to the next space
            source.get(c);
            }
            //TO DO ??????              // but now I don't know how to read the floats          
        }
        else if(c == 'r'){              // only two floats needed
            float x;
            float y;
            while(c != ' '){            // go to the next space
            source.get(c);
            }
            //TO DO ??????
        }                                
        else if(c == 'p'){              // only one float needed
            float x;
            while(c != ' '){            // go to the next space
            source.get(c);
            }
            //TODO ???????
        }
        else{
            cerr << "Unknown shape!\n";
        }
    }   
 return 0;
}

【问题讨论】:

  • 你试过sscanf()吗?
  • 另外,您的文本文件中的几行代码可能有助于验证人们提出的任何代码。
  • @jedwards 考虑到它是 C++,sscanf 不会比这个 getc 垃圾好多少。

标签: c++ file text floating-point


【解决方案1】:

为什么不以通常的方式使用 C++ 流而不是所有这些 getc 疯狂:

#include <sstream>
#include <string>

for(std::string line; std::getline(source, line); )   //read stream line by line
{
    std::istringstream in(line);      //make a stream for the line itself

    std::string type;
    in >> type;                  //and read the first whitespace-separated token

    if(type == "triangle")       //and check its value
    {
        float x, y, z;
        in >> x >> y >> z;       //now read the whitespace-separated floats
    }
    else if(...)
        ...
    else
        ...
}

【讨论】:

    【解决方案2】:

    这应该可行:

    string shapeName;
    source >> shapeName;
    if (shapeName[0] == 't') {
        float a,b,c;
        source >> a;
        source >> b;
        source >> c;
    }
    

    【讨论】:

      猜你喜欢
      • 2018-09-08
      • 2021-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多