你好,我有一个关于这个函数recup()
的问题。recup()
的目的是将字符串chaine
中的所有单词逐个插入到数据库中。这些单词来自用户使用fgets设置的chaine。我面临的问题是,它只插入与chaine
的第一个单词具有相同长度的单词。例如,如果我写"I want a cat",则只会插入"I“和"a”。
int recup(char *chaine){
char tab[30] ={0};
char delim[] = " ";
char *ptr = strtok(chaine,delim);
int rc =0;
char *sql ="INSERT INTO newTable SELECT * FROM dbTable where lemme =?";
sqlite3_stmt *stmt = 0;
rc = sqlite3_prepare_v2(db,sql,-1,&stmt,0);
do {
// Expected word is printed here
printf("%s\n",ptr);
strcpy(tab,ptr);
// For some reason, only words that match the length
// of the first word are being inserted
rc = sqlite3_bind_text(stmt,1,tab,-1,SQLITE_STATIC);
rc = sqlite3_step(stmt);
ptr = strtok(NULL,delim);
} while(ptr != NULL);
rc = sqlite3_finalize(stmt);
return 0;
}
#include <ansi_c.h>
#include <sqlite3.h>
#include "fdata.h"
sqlite3 *db;
int main(int argc, char* argv[]) {
int rc = 0;
char chaine[100] = {0};
rc = sqlite3_open("lexique.db",&db);
check(rc);
createNewT();
question(&chaine);
recup(&chaine);
sqlite3_close(db);
return 0;
}
发布于 2019-03-18 19:06:10
函数的作用是:修改传入的字符串。因此,有必要创建输入字符串的副本。请参阅@David Cullen的优秀答案,它创建了一个mcve。
请参阅已更正代码中的注释,这些注释解释了正在发生的情况。
#include <stdio.h>
#include <string.h>
int recup(char *chaine){
char tab[30] ={0};
char delim[] = " ";
///// strtok will modify its inut string argument, so create a copy of the input
strcpy(tab, chaine);
// ptr will contain the current last token that was parsed
char *ptr = strtok(tab,delim); // pass the copy to strtok, ptr points to first word
int rc =0;
char *sql ="INSERT INTO newTable SELECT * FROM dbTable where lemme =?";
sqlite3_stmt *stmt = 0;
rc = sqlite3_prepare_v2(db,sql,-1,&stmt,0);
while (ptr) {
printf("%s\n",ptr); // print the word that was just tokenized
rc = sqlite3_bind_text(stmt,1,ptr,-1,SQLITE_STATIC);
rc = sqlite3_step(stmt);
ptr = strtok(NULL,delim);
}
rc = sqlite3_finalize(stmt);
return 0;
}
https://stackoverflow.com/questions/55218499
复制相似问题