不工作代码:
#include "stdafx.h"
#include <stdio.h>
#include "sqlite3.h"
#include <Windows.h>
#include <string>
#include <iostream>
#include <vector>
using namespace std;
std::vector<string> emailsfound;
static int callback(void *data, int argc, char **argv, char **azColName)
{
int i;
string thefile;
for(i=0; i<argc; i++)
{
thefile = string(argv[i]);
size_t found = thefile.find(":");
if(found != std::string::npos)
{
thefile.erase(thefile.begin(), thefile.begin()+1);
emailsfound.push_back(thefile);
//here's the problem
cout << emailsfound[i] << endl; //here it only couts emailsfound[0] over and over until the loop's work is done.
}
else
{
}
}
return 0;
}
int main(int argc, char* argv[])
{
sqlite3 *db;
char *zErrMsg = 0;
int rc;
char *sql;
const char* data = "Callback function called"; //I am not printing this
/* Open database */
rc = sqlite3_open("C:\\Users\\main.db", &db);
if( rc )
{
return 0;
}
else
{
}
/* Create SQL statement */
sql = "SELECT emails from People";
/* Execute SQL statement */
rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg);
if( rc != SQLITE_OK )
{
sqlite3_free(zErrMsg);
return 0;
}
else
{
}
sqlite3_close(db);
system("PAUSE");
return 0;
}
工作代码:
#include "stdafx.h"
#include <stdio.h>
#include "sqlite3.h"
#include <Windows.h>
#include <string>
#include <iostream>
#include <vector>
using namespace std;
std::vector<string> emailsfound;
static int callback(void *data, int argc, char **argv, char **azColName)
{
int i;
string thefile;
for(i=0; i<argc; i++)
{
thefile = string(argv[i]);
size_t found = thefile.find(":");
if(found != std::string::npos)
{
thefile.erase(thefile.begin(), thefile.begin()+1);
emailsfound.push_back(thefile);
//Doing this makes it works great.
printthevector();
}
else
{
}
}
return 0;
}
void printthevector()
{
int sizeofthevector;
int i = 0;
sizeofthevector = emailsfound.size();
while (i < sizeofthevector)
{
cout << emailsfound[i].c_str() << endl; //print everything / it works great
}
}
int main(int argc, char* argv[])
{
sqlite3 *db;
char *zErrMsg = 0;
int rc;
char *sql;
const char* data = "Callback function called"; //I am not printing this
/* Open database */
rc = sqlite3_open("C:\\Users\\main.db", &db);
if( rc )
{
return 0;
}
else
{
}
/* Create SQL statement */
sql = "SELECT emails from People";
/* Execute SQL statement */
rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg);
if( rc != SQLITE_OK )
{
sqlite3_free(zErrMsg);
return 0;
}
else
{
}
sqlite3_close(db);
system("PAUSE");
return 0;
}
正如您所看到的,在第一个代码中,由于某种原因,它只会反复计算emailsfound [0]因此我必须创建一个适当的空白来cout所有正确找到的电子邮件。 请向我解释一下,我知道我修好了,但我不确定为什么第一个代码无效。