简体   繁体   English

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

[英]C++ read from a text file and seperate it into variables

This is a block of code from a program im currently writing这是我当前正在编写的程序中的一段代码

//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;

}

And this is my text file这是我的文本文件

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

By the use of a dilimiter it returns the following通过使用分界符,它返回以下内容

70:1.20:4.90:3

So far the program successfully reads a text file "Builders.txt" and with a dilimiter, splits at the fulltop to differentiate between each record and stores it in a vector.到目前为止,该程序成功读取了一个文本文件“Builders.txt”,并使用一个分隔符,在整个顶部拆分以区分每条记录并将其存储在一个向量中。 What im trying to do right now is assign each element thats seperated by a colon to a variable.我现在要做的是将用冒号分隔的每个元素分配给一个变量。 So for example, Reliable Rover is the name 70 is the ability and 1 is the variability.例如,Reliable Rover 是名称,70 是能力,1 是可变性。 In my code above i have attempted this through the line在我上面的代码中,我尝试了这个

ss >> name >> ability >>  variability; 

But when i go to return a value using cout it only only returns the ability and variaiblity但是当我 go 使用 cout 返回一个值时,它只返回能力和可变性

Thankyou.谢谢你。

You should use your outer loop to read a line, and your inner loop to split it using your delimiter.您应该使用外部循环读取一行,并使用您的内部循环使用分隔符将其拆分。
Right now, your inner loop just removes the '.'现在,您的内部循环只是删除了“。” at the end of each line.在每一行的末尾。
Try something along the lines of:尝试以下方式:

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";

}

Add error-checking as needed (eg for stoi )根据需要添加错误检查(例如对于stoi

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM