2011-12-07 13 views
14

¿Cómo puedo leer carrozas de un archivo .txt? Dependiendo del nombre al comienzo de cada línea, quiero leer un número diferente de coordenadas. Las carrozas están separadas por "espacio".Leer carrozas de un archivo .txt

Ejemplo: triangle 1.2 -2.4 3.0

El resultado debe ser: float x = 1.2/float y = -2.4/float z = 3.0

El archivo tiene más líneas con differens formas que pueden ser más complejo, pero creo que si sé cómo hacer uno de ellos que pueda hacer los otros por mi cuenta

mi código hasta ahora:

#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

Tener usted probó [sscanf()] (http://www.cplusplus.com/reference/clibrary/cstdio/sscanf/)? – jedwards

+0

Además, algunas líneas de su archivo de texto pueden ayudar a validar cualquier código que la gente proponga. – jedwards

+0

@jedwards Teniendo en cuenta que es C++, 'sscanf' no será mucho mejor que esta basura' getc'. –

Respuesta

22

no ¿Por qué sólo tiene que utilizar C++ corrientes de la manera habitual en lugar de todo esto getc locura:

#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

Perfecto, muchas gracias !!! Eso me ahorró mucho trabajo, todavía soy nuevo con C++: D – user1053864

5

Esto debería funcionar:

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