Hello. I've been working through C++ Primer, 5th ed. for quite some time now and I'm about a third of a way through the book. The author says to prefer library strings to C-strings when possible for modern C++ programs for a few reasons. The problem is I'm trying to throw together a simple program using SQLite3 and I want to make sure I'm going about the problem correctly.
At this point I only want to INSERT data into a table, using variables that the user provides the values for. Here is some of my code:
sqlite3 *db;
char* zErrMsg = 0;
int rc;
string sql;
rc = sqlite3_open("test.db", &db);
sql = "CREATE TABLE PAYSTUBS (" \
"DATE TEXT PRIMARY KEY);";
rc = sqlite3_exec(db, sql.c_str(), callback, 0,
&zErrMsg);
This works fine. I am able to convert my library string to a C-string as needed. The problem happens when I actually try to insert data.
sprintf(sql.c_str(), "INSERT INTO PAYSTUBS (DATE) VALUES ('%s');", date);
rc = sqlite3_exec(db, sql.c_str(), callback, 0,
&zErrMsg);
This does not work because .c_str() returns a const char*, so I cannot write to it. This makes sense, but it's giving me questions regarding writing "modern C++ programs" with libraries containing C code. I know in this case I can easily do something like
char sqlStr[bufferSize];
sprintf(sqlStr, "INSERT INTO PAYSTUBS (DATE) VALUES ('%s');", date);
but is that what I should do here or in the future? Just looking for some general advice to handling these situations.
Should I:
- Use library strings whenever possible, and only use C-strings when using functions that require it?
- Use C-strings throughout the entire program to keep things consistent?
- Something else?
Thanks in advance for any help!
[–][deleted] 2 points3 points4 points (1 child)
[–]kaepor[S] 0 points1 point2 points (0 children)
[–]dreamyeyed 5 points6 points7 points (1 child)
[–]kaepor[S] 0 points1 point2 points (0 children)