2015-12-13 3 views
-1

Итак, я считаю, что значения из текстового файла попадают в вектор «com», то, что я пытаюсь сделать, это распознавать направление, затем принимать значение рядом с направлением, tmp, продолжить чтение, если направление повторяется снова, добавьте переменную комбайна, затем переопределите переменную tmp, установите конечную переменную tmp, которая будет передана другому классу. Если Repeat было «увидеть» это выглядит на последнем направлении используется и принять значение повтора и добавить его в последнее направление используется, любая помощь будет оценена, извините за путаницу в опросеC++ - подсчет значений и передаваемых значений в векторе

file1.txt:

Forward 2 
Left 20 
Forward 1 
Repeat 3 

fileReader.cpp

#include <iostream> 
#include <float> 
#include <vector> 

using namespace std; 

int main() 
{ 
    ifstream file("text1.txt");  
    string word; 
    vector<float> com; 

    while (file >> word) 
    { 
     if(std::find(std.begin(com), std.end(com), Forward) != com.end()) 
     { 
     } 

     if(std::find(std.begin(com), std.end(com), Jump) != com.end()) 
     { 
     } 

     if(std::find(std.begin(com), std.end(com), Left) != com.end())) 
     { 
     } 

     if(std::find(std.begin(com), std.end(com), Right) != com.end())) 
     { 
     } 

     if ((std::find(std.begin(com), std.end(com), Repeat) != com.end())) 
     { 
     } 
    }  
} 
+0

C не C++ не C! И правильно отформатируйте свой код. – Olaf

ответ

0

Вы можете использовать карту для разбора ввод:

int main() 
{ 
    ifstream file("text1.txt");      //open file 
    if(!file) { /* file could not be opened */ }  //and check whether it can be used 

    std::map<std::string, float> com; 
    std::string lastCom;        //last command for use in "Repeat" 

    std::string line; 
    while (std::getline(file, line))     //read a line at once until file end 
    { 
     if(line.empty()) continue;     //and continue if it is empty 

     std::string tempCom; 
     float tempVal; 

     std::stringstream ss(line);     //extract command and value 
     ss >> tempCom; 
     ss >> tempVal; 

     if(tempCom == "Repeat") 
     { 
      com[lastCom] += tempVal;     //add the value to the last command 
     } 
     else 
     { 
      com[tempCom] += tempVal;     //add the value to the current command 
      lastCom = tempCom;      //and update last command 
     } 
    }  
} 

Код не проверен.

+0

Спасибо, объединив его с некоторым кодом обратной связи, его работы :) – Minto

0

Ну, я предпочел переписать код с нуля, используя другой контейнер вместо заполнения бланков:

#include <iostream> 
#include <map> 
#include <fstream> 
#include <string> 

int main() { 
    std::map<std::string,int> moves{{"Forward", 0}, {"Left", 0}, {"Right", 0}, 
            {"Jump", 0 }, {"Repeat", 0}}; 

    auto iRepeat = moves.find("Repeat"); 
    auto iold = moves.end(); 

    std::ifstream iFile("text1.txt"); 
    if (!iFile.good()) return 1; 

    std::string s; 
    int x;      // There aren't floats in your file... 
    while (iFile >> s >> x) { 
     auto im = moves.find(s); 
     if (im == iRepeat) { 
      if (iold == moves.end()) continue; // there must be a move to repeat 
      iold->second += x; 
     } else if (im != moves.end()){ 
      im->second += x;      // update the move 
      iold = im; 
     } 
    } 

    iFile.close(); 

    for (auto i = moves.begin(); i != moves.end(); i++) { 
     if (i != iRepeat)  // shows only the moves 
      std::cout << i->first << ": " << i->second << std::endl; 
    } 

    return 0; 
} 

Выход:

Forward: 6 
Jump: 0 
Left: 20 
Right: 0 
Смежные вопросы