2011-12-07 22 views
14

Bir .txt dosyasındaki floatları nasıl okuyabilirim? Her satırın başlangıcındaki ada bağlı olarak, farklı bir koordinat numarası okumak istiyorum. Yüzer "boşluk" ile ayrılmış.Bir .txt dosyasından okunan bilgileri oku

Örnek: triangle 1.2 -2.4 3.0

sonucu olmalıdır: float x = 1.2/float y = -2.4/float z = 3.0

dosya daha karmaşık olabilir differens şekiller başka satırlar var ama yapabileceğim bunlardan birini nasıl biliyorsanız bence diğerleri kendi başıma. Bugüne kadar

Benim Kodu:

#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

Var denediniz [sscanf()] (http://www.cplusplus.com/reference/clibrary/cstdio/sscanf/)? – jedwards

+0

Ayrıca, metin dosyanızdan birkaç satır, kullanıcıların önerdiği herhangi bir kodu doğrulamaya yardımcı olabilir. – jedwards

+0

@jedwards C++ olduğunu düşünürsek, sscanf bu "getc" çöplüğünden daha iyi olmayacaktır. –

cevap

22

sadece C++ zamanki şekilde akışları kullanmayın yerine neden tüm bu getc delilik:

#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

Mükemmel, çok teşekkürler !!! Bu beni çok çalıştı, C++ ile hala yeni yaşıyorum: D – user1053864

5

Bu çalışması gerekir:

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