正如TomWij所说,你先做ifstream然后strtok,但我建议你用“”转义你的字符串,而不仅仅是空格,这样你就可以存储“这样的东西,例如关于用户的注释”,这就是它的完成方式使用 CSV(逗号分隔值)。
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <vector>
using namespace std;
void readCSV(std::istream &input, std::vector< std::vector<std::string> > &output)
{
std::string csvLine;
// read every line from the stream
while( std::getline(input, csvLine) )
{
std::istringstream csvStream(csvLine);
std::vector<std::string> csvColumn;
std::string csvElement;
// read every element from the line that is seperated by commas
// and put it into the vector or strings
while( std::getline(csvStream, csvElement, ',') )
{
csvColumn.push_back(csvElement);
}
output.push_back(csvColumn);
}
}
int main()
{
std::fstream file("file.csv", ios::in);
if(!file.is_open())
{
std::cout << "File not found!\n";
return 1;
}
// typedef to save typing for the following object
typedef std::vector< std::vector<std::string> > csvVector;
csvVector csvData;
readCSV(file, csvData);
// print out read data to prove reading worked
for(csvVector::iterator i = csvData.begin(); i != csvData.end(); ++i)
{
for(std::vector<std::string>::iterator j = i->begin(); j != i->end(); ++j)
{
std::cout << *j << ", ";
}
std::cout << "\n";
}
}
这让我想到了真正的解决方案,为什么不使用CSV 模块或更好的 CSV 库,SQLite,SQLite 非常易于安装和使用,而且它比手动编写数据库更好,除了它应该将SQLite加入您的代码库不会花费您超过 1 小时,因为它的 API 非常简单。
#include <stdio.h>
#include <sqlite3.h>
static int callback(void *NotUsed, int argc, char **argv, char **azColName){
int i;
for(i=0; i<argc; i++){
printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
}
printf("\n");
return 0;
}
int main(int argc, char **argv){
sqlite3 *db;
char *zErrMsg = 0;
int rc;
if( argc!=3 ){
fprintf(stderr, "Usage: %s DATABASE SQL-STATEMENT\n", argv[0]);
exit(1);
}
rc = sqlite3_open(argv[1], &db);
if( rc ){
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
sqlite3_close(db);
exit(1);
}
rc = sqlite3_exec(db, argv[2], callback, 0, &zErrMsg);
if( rc!=SQLITE_OK ){
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
}
sqlite3_close(db);
return 0;
}