C ++从文本文件中读取并将其分成变量

时间:2020-04-09 06:29:45

标签: c++ file

这是当前正在编写的程序的代码块

//declaration of builder variables
std::string name;
int ability;
int variability;

std::vector<string> builderVector;


std::ifstream buildersList("Builders.txt");
std::string outputFile = "output.txt";
std::string input;

void readFile() //function to read Builders file
{

   std::string line;

// read each line for builders
while (std::getline(buildersList, line)) {

    std::string token;
    std::istringstream ss(line);

    // then read each element by delimiter
    while (std::getline(ss, token, ':')) //spilt the variables 

      ss >> name >> ability >>  variability; 
      builderVector.push_back(token);
      cout << name;

}

这是我的文本文件

Reliable Rover:70:1.
Sloppy Simon:20:4.
Technical Tom:90:3.

通过使用分隔符,它返回以下内容

70:1.20:4.90:3

到目前为止,该程序已成功读取文本文件“ Builders.txt”,并带有一个分隔符,并在全顶分割以区分每个记录并将其存储在vector中。我现在想做的就是将由冒号分隔的每个元素分配给一个变量。因此,例如,“可靠的漫游者”是70的能力,而1是变异性。在上面的代码中,我已尝试通过该行

ss >> name >> ability >>  variability; 

但是当我使用cout返回值时,它仅返回能力和可变性

谢谢。

1 个答案:

答案 0 :(得分:2)

您应该使用外循环读取一行,并使用内循环使用定界符将其分割。
现在,您的内部循环仅删除了“。”。在每一行的末尾。
尝试以下方法:

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

    // 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:
        name = token;
        break;
      case 1:
        ability = stoi(token);
        break;
      case 2:
        variability = stoi(token);
        break;
      default:
        break;
      }
      counter++;//increasing counter
    }
    cout << name<<" "<<ability<<" "<<variability<<"\n";

}

根据需要添加错误检查功能(例如stoi