使用 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;
}