我需要从文件中读取由逗号示例分隔的一系列信息。
猎户座,33000,30000,18,5.9
Spica,22000,8300,10.5,5.1
我很难弄清楚getline结构来完成这个工作。实验室里的CS导师说要用getline来做这件事,但我似乎不能让它工作(visual在这个函数中不认识getline )
#include <iostream>
#include <fstream>
#include "star.h"
#include <string>
using namespace std;
char getChoice();
void processSelection(char choice);
void processA();
(skipping crap you don't need)
static char filePath[ENTRY_SZ];
void processA() {
ifstream openFile;
long temp, test;
double lum, mass, rad;
char name;
cout << "Please enter the full file path" << endl;
cin >> filePath;
openFile.open(filePath, ios::in);
if (openFile.good() != true) {
cout << "this file path was invalid";
}
while (openFile.good())
{
star *n = new star;
// getline(openFile, name, ',');
star(name);
getline(openFile, temp, ',');
n->setTemperature(temp);
getline(openFile, lum, ',');
n->setLuminosity(lum);
getline(openFile, mass, ',');
n->setMass(mass);
cin >> rad;
n->setRadius(rad);
}
}从我在网上读到的内容(包括较老的帖子)和我的CS导师所说的,这应该是有效的,所以任何帮助都将受到感谢。
发布于 2016-02-21 09:07:42
使用std::getline()的建议可能意味着您首先阅读std::string,然后处理该std::string的内容,例如使用std::istringstream。
我建议不要使用std::getline(),当然,在读取输入后也要检查它们。要处理非std::string字段后的逗号分隔符,我需要使用一个自定义操作程序:
std::istream& comma(std::istream& in) {
if ((in >> std::ws).peek() == ',') {
in.ignore();
}
else {
in.setstate(std::ios_base::failbit);
}
return in;
}该机械手跳过前导空格(使用机械手std::ws),然后简单地检查下一个字符是否为逗号。如果是,则提取逗号,否则流将被设置为失败模式,进一步的读取尝试将失败,直到处理失败状态(例如,使用in.clear()并可能删除任何违规字符)。
有了这个机械手,就可以很容易地读取相应的值。注意,当从格式化的输入切换到未格式化的输入时,很可能需要忽略前导空格(例如,在本例中为换行)。另外,下面的代码第一次尝试读取值并仅在此尝试成功时才使用它们:输入将始终在读取尝试之后进行检查,而不是在此之前!
// ...
long temp;
double lum, mass, rad;
std::string name;
while (std::getline(in >> std::ws, name, ',')
>> temp >> comma
>> lum >> comma
>> mass >> comma
>> rad) {
// use the thus read values
}https://stackoverflow.com/questions/35533447
复制相似问题