首页 > 解决方案 > 将字符串拆分为标记并将标记分成两个单独的数组

问题描述

我正在尝试创建一个函数 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){

            }
        }
    }
}

标签: c++arrayssplittoken

解决方案


使用可以检查多个分隔符的 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;
}

推荐阅读