从.txt文件读取浮动 [英] Read floats from a .txt file

查看:201
本文介绍了从.txt文件读取浮动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从.txt档案读取浮动广告。根据每行开头的名称,我想读取不同数量的坐标。

How can I read floats from a .txt file. Depending on the name at the begining of each line I want to read a different number of coordinates. The floats are seperated by "space".

例如: triangle 1.2 -2.4 3.0

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

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

The file has more lines with differens shapes which can be more complex but I think if i know how to do one of them I can do the others on my own.

我的代码到目前为止:

#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;
}


推荐答案

通常的方式而不是所有这些 getc 疯狂:

Why not just use C++ streams the usual way instead of all this getc madness:

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

这篇关于从.txt文件读取浮动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆