[英]Read floats from a .txt file
如何從.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;
}
為什么不以通常的方式使用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
...
}
這應該工作:
string shapeName;
source >> shapeName;
if (shapeName[0] == 't') {
float a,b,c;
source >> a;
source >> b;
source >> c;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.