2016-03-31 28 views
0

我有这样的条目,例如:读取文本文件,并转换为可变

TIE-Fighter (v=250, a=75, s=30, c=45) 

这是我的代码:

typedef struct { 
     string type; 
     int velocity; 
     int attack;  
     int shield;  
     int cost;  
    } Fighter; 


int main(){ 
    string nomFichero; 
    cout << "Filename:" << endl; 
    cin >> nomFichero; 
    ifstream fich(nomFichero.c_str()); 
    if (fich.is_open()){ 
    string s; 
    Fighter f; 
    while(fich>>f.type){ 
     fich >> f.velocity; 
     fich >> f.attack; 
     fich >> f.shield; 
     fich >> f.cost; 

    } 
    // cout f.type,f.attack etc... 
    fich.close(); 
    } 

} 

但它不工作...输出的东西像这样:

TIE-Fighter (v=0, a=32708, s=1963230416, c=32708) 

那么如何读取文本文件并将它们分离为变量?

+3

是否该文件有格式化为“TIE-Fighter(v = 250,a = 75,s = 30,c = 45)”?如果您将文件中的数据存储为像TIE-Fighter 250 75 30 45' – NathanOliver

+0

它可以节省您很多时间,痛苦和努力它必须是这样的......它的功课:(因为我必须导出和导入,所以必须是相同的格式 – Seokjin

+0

将行加载到一个字符串中并解析它,这里没有捷径 –

回答

0
#include <string> 
#include <fstream> 
#include <iostream> 
#include <regex> 

typedef struct { 
     std::string type; 
     int velocity; 
     int attack;  
     int shield;  
     int cost;  
} Fighter; 


int main(int argc, char** argv) 
{ 
    std::string nomFichero; 
    std::cout << "Filename:" << std::endl; 
    std::cin >> nomFichero; 
    std::ifstream fich(nomFichero.c_str()); 
    std::string currentLine; 
    std::vector<Fighter> allFighters; 
    if (fich.is_open()) 
    { 
     while (getline(fich, currentLine)) 
     { 
      std::smatch match; 
      std::regex re("(.+) \\(v=(\\d+), a=(\\d+), s=(\\d+), c=(\\d+)\\)$"); 
      int index = 0; 
      Fighter f; 
      while (std::regex_search (currentLine, match, re)) 
      { 
       for (int i = 1; i < match.size(); i++) 
       { 
        if (i == 1) f.type = match[i]; 
        else if (i == 2) f.velocity = std::stoi(match[i]); 
        else if (i == 3) f.attack = std::stoi(match[i]); 
        else if (i == 4) f.shield = std::stoi(match[i]); 
        else if (i == 5) f.cost = std::stoi(match[i]); 
       } 
       currentLine = match.suffix().str(); 
       allFighters.push_back(f); 
      } 
     } 
     fich.close(); 
     for (Fighter& f : allFighters) 
      std::cout << f.type << ", " << f.attack << ", " << f.shield << ", " << f.cost << std::endl; 
    } 
} 

这是我使用正则表达式小的解决方案,它可以在一个文件中读取多个战士:

例如:

TIE-Fighter (v=250, a=75, s=30, c=45) 
COOL-Fighter (v=400, a=60, s=90, c=55) 

将输出:

TIE-Fighter, 75, 30, 45 
COOL-Fighter, 60, 90, 55 
相关问题