c++ - 使用 ifstream 读取带逗号的 .txt 文件
问题描述
基于 ifstream 我使用以下函数来读取 filename.txt 文件
//reading from text file
static std::vector<double> vec;
double a[18]; //values got read from txt file
int i = 0;
void readDATA()
{
double value;
std::ifstream myFile;
myFile.open("filename.txt", std::ios::app);
if (myFile.is_open())
{
std::cout << "File is open." << std::endl;
while (myFile >> value)
{
vec.push_back(value);
std::cout << "value is " << value << std::endl;
a[i] = value;
std::cout << "a" << i << "=" << a[i] << std::endl;
i = i + 1;
}
myFile.close();
}
else
std::cout << "Unable to open the file";
}
它工作正常以下是 filename.txt 文件的内容:
0 0 40 45 15
0 1 40 -45 10
0 0 180 90 15
您能否帮我修改函数,以便我可以读取相同的 .txt 文件,元素之间用逗号分隔?
解决方案
您想读取数字后跟冒号吗?
定义将处理此“任务”的类:
struct Number
{
double value;
operator double() const { return value; }
};
std::istream& operator >>(std::istream& is, Number& number)
{
is >> number.value;
// fail istream on anything other than ',' or whitespace
// end reading on ',' or '\n'
for (char c = is.get();; c = is.get()) {
if (c == ',' or c == '\n')
break;
if (std::isspace(c))
continue;
is.setstate(std::ios_base::failbit);
break;
}
return is;
}
然后在您的代码中 - 替换double value;
为Number value;
推荐阅读
- javascript - 在javascript中更改输入数字时如何使值自动更新?
- php - 如何在 Apache 2.4.46 上启用 HTTP 请求标头
- excel - 如何使用 VBA 轻松将 CSV 文件输入 Excel?
- php - laravel excel导出 - 数据存储为文本而不是数字
- c# - C#:使用 foreach 和数组元素组合 2 个列表
- javascript - 我们如何在 beforeEach 中正确初始化 Cypress 拦截?
- rust - 构建失败并出现错误:Pear 需要 rustc 的“开发”或“夜间”版本,即使在夜间成功设置了 rustup 覆盖后也是如此
- google-apps-script - 如何一次提取数据并写入 50 行的单元格?(YouTube 视频统计查询限制解决方法)
- ruby - 如何用国家宝石列出所有大陆?
- java - JavaFx 关闭阶段不可预知的行为