2011-12-07 15 views
14

Jak mogę odczytać zmienne z pliku .txt. W zależności od nazwy na początku każdej linii chcę przeczytać inną liczbę współrzędnych. Pływaki są oddzielone "spacją".Czytaj pływaki z pliku .txt

Przykład: triangle 1.2 -2.4 3.0

Wynik powinien być: float x = 1.2/float y = -2.4/float z = 3.0

Plik ma więcej linii z differens kształtach, które mogą być bardziej złożone, ale myślę, że jeśli wiem, jak to zrobić jeden z nich można zrobić inni na własną rękę.

mój kod do tej pory:

#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

Have próbowałeś [sscanf()] (http://www.cplusplus.com/reference/clibrary/cstdio/sscanf/)? – jedwards

+0

Również kilka linii z pliku tekstowego może pomóc w sprawdzeniu poprawności każdego proponowanego kodu. – jedwards

+0

@jedwards Biorąc pod uwagę, że to C++, 'sscanf' nie będzie dużo lepszy niż te' getc' śmieci. –

Odpowiedz

22

Dlaczego nie wystarczy użyć C++ strumieni zwykły sposób, zamiast całej tej getc szaleństwa:

#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

Doskonały, wielkie dzięki! To zaoszczędziło mi dużo pracy, wciąż jestem nowy z C++: D – user1053864

5

To powinno działać:

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