从.txt文件中读取浮点数

时间:2011-12-07 19:19:52

标签: c++ file text floating-point

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

示例: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;
}

2 个答案:

答案 0 :(得分:24)

为什么不以通常的方式使用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
        ...
}

答案 1 :(得分:6)

这应该有效:

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