c++ - 如何在 getline() 中使用多个分隔符 (',' , '/n')?
问题描述
我正在尝试使用 fstream 在我的代码中读取文本文件。文本文件具有以下结构,
Main,Johnsons,4,4
Lake,Smiths,1,2
Orchid,Hendersons,3,8
我正在尝试执行以下操作。
Neighborhood n1;
ifstream houses;
houses.open("houses.txt");
string line;
string street;
string family;
int house;
int rooms;
int colptr = 1;
while (houses.good()) {
getline(houses, line, ',');
switch (colptr) {
case 1: {
col1 = line;
colptr++;
break;
}
case 2: {
col2 = line;
colptr++;
break;
}
case 3: {
col3 = stoi(line);
colptr++;
break;
}
case 4: {
col4 = stoi(line);
colptr = 1;
House h(col1, col2, col3, col4);
n1.addHouse(h);
break;
}
default: {
break;
}
}
}
House 是一个使用 (string,string,int,int) 构造 House 的类,Neighborhood 类的方法 addHouse() 只是将 House 添加到房屋列表中。
该代码会引发错误,因为它试图将字符串转换为 int。我在第 4 次迭代中发现它会尝试将“4 Lake”转换为整数——这显然是做不到的。
如果在最后使用“,”格式化我的文本文件,则该代码有效
Main,Johnsons,4,4,
除了这对我不起作用,因为我得到的文本文件总是像开头显示的那样。
先感谢您!
解决方案
getline()
您可以在嵌套循环中调用两次。第一个通常“逐行”读取输入,第二个在std::stringstream
对象的帮助下用逗号“,”分割:
//...
while (houses.good()) {
getline(houses, line); //use default getline() - line by line
std::stringstream ss (line);
std::string word;
while (getline (ss, word, ',')) {
//... the rest of code
//...
推荐阅读
- python - sckit-learn RandomizedSearchCV 在使用 KerasRegression 时没有属性“best_estimator_”
- telethon - 数据库锁定的异常名称
- javascript - React.js 全局变量在路由上擦除
- jquery - 同时滚动两个 Swiper Slider 幻灯片
- php - 为什么我的自定义 Laravel 路由不起作用?
- micronaut - 可以在 HTTP micronaut 声明式客户端中更改服务器吗?
- google-bigquery - BigQuery CLI:加载命令处于待处理状态
- r - 如何更改 R 中数据框的行索引和列索引?
- python - 如何使用 RF 预测离散值目标变量?
- node.js - 在 nodejs 中为 azure redis 缓存编写单元测试