C ++ For循环仅处理向量列表的最终条目

时间:2020-04-12 07:21:31

标签: c++ file vector

在主程序中,我有一个类似于以下内容的函数

for(int i = 0; i < partsVector.size(); i++) {

if(newChar == "A") {

 cout << newChar <<  endl;
} else {
  cout << "Character not found";
}

} 

程序将参考此文本文件运行,该文本文件本身已存储在向量中(因此,partsVector)(PS我仅在我停下并有issus时才将partCode添加到列表中)

A:Head:1:2:15.
B:Torso:0:6:5.
C:Leg:0:4:6.
D:Arm:0:4:8.
E:Tail:0:6:2.

关于此代码段(我将包括完整的程序),问题是它运行时返回“不存在字符”,当newChar为A时返回,如文本文件中所示,有一个示例存在。我可以通过增强的for循环打印矢量列表,它会按预期返回。 我想知道我的循环在向量列表中停留并停在最后一个条目,而仅在测试条件时使用它吗?

完整代码

主要

include "driver.h"
#include "implementation.cpp"
#include <fstream>
#include <vector>
using namespace std;

int main() {

readFile();
writeFile();
robotComplexity();


getch();
return 0;

}

实施

#include <iostream>
#include <string>
#include <sstream> 
#include <fstream>
#include <fstream>
#include <vector>
using namespace std;

//declaration of parts variables
char partCode;
std::string partName;
int maximum;
int minimum;
int complexity;

std::vector<string> partsVector;
std::ifstream partsList("Parts.txt");
std::string outputFile = "output.txt";
std::string input;

std::string newChar;
std::stringstream convertChar;

void readFile() 
{

   std::string line;

while (std::getline(partsList, line)) {
    line.pop_back();//removing '.' at end of line
    std::string token;
    std::istringstream ss(line);

    convertChar << partCode;
    convertChar >> newChar;

    // then read each element by delimiter
    int counter = 0;//number of elements you read
    while (std::getline(ss, token, ':')) {//spilt into different records
      switch (counter) {//put into appropriate value-field according to element-count

      case 0:
        newChar = token; //convert partCode from a char to a string 
        break;
      case 1:
        partName = token;
        break;
      case 2: newChar2 = token;
        break;
      case 3: minimum = stoi(token);
        break;
        case 4: complexity = stoi(token);
        break;
      default:
        break;
      }
      counter++;//increasing counter
    }
partsVector.push_back(newChar);
   } 

double robotComplexity() { 

double complexity = 10;

for(int i = 0; i < partsVector.size(); i++) {

if(newChar == "A") {
 cout << newChar <<  endl;
} else {
  cout << "Character not found";
}

} 
   if(complexity > 100) {
      complexity = 100;
   }

cout << "\nThe Robot Complexity is: " << complexity << endl;
return complexity;
} 

}

我遇到问题的代码的主要功能是遍历向量列表,直到找到partCode的实例,然后将其转换为字符串,现在称为newChar,它等于A。一直到结尾(即,IE等于“ E”时)并在那里停止,仅将其用于比较。 谢谢您的帮助

0 个答案:

没有答案