2011-12-07 113 views
14

如何從.txt文件讀取浮動圖形。根據每行開頭的名稱,我想讀取不同數量的座標。浮標由「空間」分隔。從.txt文件讀取浮動圖形

例子:triangle 1.2 -2.4 3.0

結果應該是: float x = 1.2/float y = -2.4/float z = 3.0

文件還有更多線條與differens形狀可以是更復雜的,但我想如果我知道該怎麼做其中的一個我能做到其他人都是我自己的。

到目前爲止我的代碼:

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

有你試過[sscanf()](http://www.cplusplus.com/reference/clibrary/cstdio/sscanf/)? – jedwards

+0

此外,您的文本文件中的幾行可能有助於驗證人們提出的任何代碼。 – jedwards

+0

@jedwards考慮到它是C++,'sscanf'不會比這個'getc'垃圾好得多。 –

回答

22

爲什麼不直接使用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

完美,非常感謝!這爲我節省了很多工作,我仍然用C++新增:D – user1053864

5

這應該工作:

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