读取文本文件并转换为变量

时间:2016-03-31 17:53:45

标签: c++

我有这个条目,例如:

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)

那么如何读取文本文件并将它们分成这些变量呢?

1 个答案:

答案 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