【发布时间】: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 >> name >> ability >> variability;使用iostream 读取相同的值?分隔符似乎是':'而不是'.'?读取每个token后,您需要分配给name、ability或variability之一(使用std::stoi表示整数)不再使用iostream 从ss读取。请提供A Minimal, Complete, and Verifiable Example (MCVE)。 -
@AMIR 我已经完成了这一步。这不是我要求的,但谢谢你