c++ - 从 .txt 文件中读取 float

标签 c++ file text floating-point

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

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

最佳答案

为什么不直接使用 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
        ...
}

关于c++ - 从 .txt 文件中读取 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8421170/

相关文章:

php - 如何从 COM DLL 返回包含多个空字符的 BSTR

c++ - 包含 <omp.h> 的错误 (c++)

python - 文件保存问题 PYTHON - 重复文件?

c# - DllNotFoundException : TMPro_Plugin, 在 Linux 上使用 TextMesh Pro

c++ - 在 linux 中关闭 udp 套接字后 recv 不返回

c++ - C++中的64位枚举?

java - 更新文本文件而不丢失信息

java - 从 Java 过渡到 C++

mysql - 从文本文件填充 MySQL 表

text - swt文本验证