【问题标题】:C++ read from a text file and seperate it into variablesC ++从文本文件中读取并将其分成变量
【发布时间】:2020-04-09 06:29:45
【问题描述】:

这是我正在编写的程序中的一段代码

//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”,并使用分隔符在整个顶部拆分以区分每条记录并将其存储在一个向量中。我现在要做的是将用冒号分隔的每个元素分配给一个变量。例如,Reliable Rover 是名称,70 是能力,1 是可变性。在我上面的代码中,我尝试了这一行

ss >> name >> ability >>  variability; 

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

谢谢。

【问题讨论】:

  • 为什么在这里while (std::getline(ss, token, '.')) //spilt into different records 使用getline 读取,然后在ss &gt;&gt; name &gt;&gt; ability &gt;&gt; variability; 使用iostream 读取相同的值?分隔符似乎是 ':' 而不是 '.'?读取每个token 后,您需要分配给name、ability 或variability 之一(使用std::stoi 表示整数)不再使用iostream 从ss 读取。请提供A Minimal, Complete, and Verifiable Example (MCVE)。
  • 这能回答你的问题吗? How to split the elements of a text file in C++
  • @AMIR 我已经完成了这一步。这不是我要求的,但谢谢你

标签: c++ file


【解决方案1】:

您应该使用外部循环读取一行,并使用您的内部循环使用分隔符将其拆分。
现在,您的内部循环只是删除了“。”在每一行的末尾。
尝试以下方式:

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-19
    • 2013-08-07
    • 2023-03-30
    • 2019-05-24
    • 2018-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多