c++ - 将字符串拆分为标记并将标记分成两个单独的数组
问题描述
我正在尝试创建一个函数 readBooks,它打开一个输入文件流,读取由逗号分隔的书籍和作者列表,文件的每一行都有 1 本书和作者对(例如:Douglas Adams,The Hitchhiker's Guide to银河)。我在如何标记或拆分字符串时遇到问题,以便我可以使用逗号作为分隔符将作者和书名插入两个单独的数组中。任何帮助表示赞赏。
数组的大小由函数中的容量参数定义。数组是在调用 readBooks() 函数之前分配的,因此不需要动态分配它们。
这是我到目前为止的代码:
int readBooks (string filename, string titles[], string authors[], int books, int capacity){
ifstream file;
file.open (filename);
if (file.fail()){
return -1;
}
else{
int i = 0;
int j = 0;
while (i < capacity){
string line;
getline (file, line);
if (line.length() > 0){
}
}
}
}
解决方案
使用可以检查多个分隔符的 boost 库,这会更简单一些。但是,您可以使用 getline() 来搜索行尾分隔符,然后使用 find() 来查找逗号。找到逗号后,您必须确保将其移过标题,并剪掉任何空白。
让我知道这是否有意义。
#include <iostream>
#include <fstream>
#include <string>
#include "readBooks.h"
#include <algorithm>
#include <cctype>
#include <locale>
/* trim from start (in place) [Trim functions borrowed from
* https://stackoverflow.com/questions/216823/whats-the-best-way-to-trim-stdstring]
*/
static inline void ltrim(std::string &s) {
s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int ch) {
return !std::isspace(ch);
}));
}
// trim from end (in place)
static inline void rtrim(std::string &s) {
s.erase(std::find_if(s.rbegin(), s.rend(), [](int ch) {
return !std::isspace(ch);
}).base(), s.end());
}
// trim from both ends (in place)
static inline void trim(std::string &s) {
ltrim(s);
rtrim(s);
}
using namespace std;
int readBooks (string filename, string titles[], string authors[], int books, int capacity){
ifstream file;
file.open (filename);
if (file.fail()){
return -1;
}
else{
int i = 0;
string line;
while( i < books && i < capacity && getline(file,line) ) {
// Find the position of the comma, and grab everything before it
string author(line.begin(), find(line.begin(), line.end(), ','));
trim(author);
authors[i] = author;
// Find position of first character after the ','
string title(find(line.begin(), line.end(), ',') + 1, line.end());
trim(title);
titles[i] = title;
i++; // increment our index
}
}
file.close();
return 0;
}
这是一个调用它的示例 main()。
#include <iostream>
#include "readBooks.h"
int main() {
const int capacity{1000};
const int books{3};
std::string authors[capacity];
std::string titles[capacity];
std::string filename{"booklist.txt"};
int retval = readBooks(filename, titles, authors, books, capacity);
return retval;
}
推荐阅读
- javascript - 在本机反应中修复未处理的承诺拒绝
- vue.js - 如何在 v-select 组件 vuetify 上设置过滤条件?
- java - 如何修复此 sql 异常
- directx - 为什么我的固定全息图不随头部移动而缩放?
- android - 如何通过匕首 2 注入使用意图值的依赖项?
- dart - 忽略子触摸,并在父小部件上接收它们
- python - 使用张量的普通最小二乘计算加速
- python - Python - 获取每个第 n 个元素(就地)
- java - 为什么 C++ 中的整数数组搜索循环比 Java 慢?
- javascript - 无法使用 React js 将数据推送和附加到状态